package com.hgkj.cloud.customer.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hgkj.cloud.base.common.PageInfo;
import com.hgkj.cloud.base.domain.*;
import com.hgkj.cloud.base.service.*;
import com.hgkj.cloud.base.util.AssertUtils;
import com.hgkj.cloud.customer.common.*;
import com.hgkj.cloud.customer.common.FileSaver;
import com.hgkj.cloud.customer.excel.AnswerExcel;
import com.hgkj.cloud.customer.excel.QuestionnaireExcel;
import com.hgkj.cloud.customer.excel.QuestionnaireExcelParseTool;
import com.hgkj.cloud.customer.excel.UserExcelParseToolNew;
import com.hgkj.cloud.customer.file.FileSourceGenerator;
import com.hgkj.cloud.customer.util.DateUtil;
import com.hgkj.cloud.base.common.PageInfoParams;
import com.hgkj.cloud.customer.common.DataGrid;
import com.hgkj.cloud.customer.common.ResponseData;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/questionnaire")
public class QuestionnaireController extends BaseController {

    @Autowired
    private SysTenantsService sysTenantsService;
    @Autowired
    private TenantQuestionnairesService tenantQuestionnairesService;
    @Autowired
    private TenantQuestionnaireTasksService tenantQuestionnaireTasksService;
    @Autowired
    private TenantQuestionnaireQuestionService tenantQuestionnaireQuestionService;
    @Autowired
    private TenantLogsService tenantLogsService;
    @Autowired
    private TenantFrameworksService tenantFrameworksService;
    @Autowired
    private TenantQuestionnaireTaskInfoService tenantQuestionnaireTaskInfoService;
    @Autowired
    private TenantQuestionnaireAnswerService tenantQuestionnaireAnswerService;
    @Autowired
    private SysTestingQuestionService mSysTestingQuestionService;
    @Autowired
    private SysTaskImagesService sysTaskImagesService;
    @Autowired
    private RemoteService remoteService;
    @Autowired
    private FileSourceGenerator fsg;
    @Autowired
    private EUserService eUserService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Value("${server.absolute.path}")
    private String serverAbsolutePath;
    @Autowired
    private ExtUsersService extUsersService;
    @Autowired
    private ExtTableSclService extTableSclService;
    @Autowired
    private ExtFieldRecordService extFieldRecordFeignService;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 获取问卷
     *
     * @param page
     * @param page_size
     * @param qname        获取问卷列表
     * @param framework_id 组织机构
     * @param admin_uuid   登陆者信息
     * @return
     */
    @RequestMapping("/getQuestionnaireList")
    @ResponseBody
    public ResponseData getQuestionnaireList(Integer page, Integer page_size, String qname, Long framework_id, String admin_uuid) {

        ResponseData mResponseData = new ResponseData();
        AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(admin_uuid);
        PageInfo pi = new PageInfo();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", qname);
//        getframeworkDatas(framework_id, adminUserInfoByUuid, map);
        getTreePathDatas(framework_id, adminUserInfoByUuid, map);

        if (page != null && page_size != null) {
            pi.setCurrentPage(page);
            pi.setPageSize(page_size);
        }
        List<Map<String, Object>> list = tenantQuestionnairesService.listQuestionnaires(pi, map);
        Long count = tenantQuestionnairesService.listQuestionnairesCount(map);
        map.clear();
        map.put("list", list);
        map.put("count", count);
        mResponseData.setData(map);
        return mResponseData;
    }

    /**
     * 删除问卷
     *
     * @param id 问卷id
     * @return
     */
    @RequestMapping(value = "/delQuestionnaire", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData delQuestionnaire(Long id, String admin_uuid) {
        String opTime = new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date());

        AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(admin_uuid);
        ResponseData mResponseData = new ResponseData();
        if (id == null) {
            mResponseData.setCode(-1);
            mResponseData.setMsg("问卷id不能为空");
            return mResponseData;
        }
        String message = null;
        TenantQuestionnaires questionnaire = tenantQuestionnairesService.findQuestionnaireById(id);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("questionnaire_id", id);
        long qnTaskInfoByQnidCount = tenantQuestionnaireTasksService.listQnTaskInfoByQnidCount(map);
        if (qnTaskInfoByQnidCount != 0) {
            mResponseData.setCode(-1);
            mResponseData.setMsg("该问卷正在使用中,请先删除其所在的问卷任务!");
            return mResponseData;
        }
        tenantQuestionnairesService.delQuestionnaire(id);
        message = "问卷：" + questionnaire.getQuestionnaire_name() + "删除成功";
        mResponseData.setMsg(message);

        return mResponseData;
    }

    /**
     * @param id 根据问卷获取问卷任务
     * @return
     */
    @RequestMapping(value = "/listQnTaskInfoByQnid")
    @ResponseBody
    public ResponseData listQnTaskInfoByQnid(Integer page, Integer page_size, Long id, String admin_uuid) {
        ResponseData mResponseData = new ResponseData();
        if (id == null) {
            mResponseData.setCode(-1);
            mResponseData.setMsg("问卷id不能为空");
            return mResponseData;
        }
        PageInfo pi = new PageInfo();

        if (page != null && page_size != null) {
            pi.setCurrentPage(page);
            pi.setPageSize(page_size);
        }

        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("questionnaire_id", id);
            List<Map<String, Object>> listQnTaskInfoByQnid = tenantQuestionnaireTasksService.listQnTaskInfoByQnid(pi, map);
            long qnTaskInfoByQnidCount = tenantQuestionnaireTasksService.listQnTaskInfoByQnidCount(map);
            map.clear();
            map.put("list", listQnTaskInfoByQnid);
            map.put("count", qnTaskInfoByQnidCount);
            mResponseData.setData(map);
        } catch (Exception e) {
            e.printStackTrace();
            mResponseData.setCode(-1);
            mResponseData.setMsg("查询失败,请稍后再试!");
        }

        return mResponseData;
    }

    /**
     * 保存问卷
     *
     * @param questionnaire_name        问卷 名
     * @param questionnaire_description 问卷描述
     * @param file                      问卷文件
     * @param admin_uuid
     */
    @RequestMapping("/saveQuestionnaire")
    @ResponseBody
    public ResponseData saveQuestionnaire(String questionnaire_name, String questionnaire_description,
                                          Double waring_score, String tag_string, Integer waring_type,
                                          @RequestParam(required = true) MultipartFile file,
                                          @RequestParam(required = true) String admin_uuid) {
        String opTime = new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date());
        ResponseData mResponseData = new ResponseData();
        TenantQuestionnaires questionnaire = new TenantQuestionnaires();
        if (StringUtils.isEmpty(questionnaire_name)) {
            mResponseData.setCode(-1);
            mResponseData.setMsg("问卷名为空");
            return mResponseData;
        }
        if (waring_type == null) waring_type = 0;
        questionnaire.setQuestionnaire_name(questionnaire_name);
        questionnaire.setQuestionnaire_description(questionnaire_description);
        if (waring_score != null)
            questionnaire.setWaring_score(waring_score);
        if (!StringUtils.isEmpty(tag_string))
            questionnaire.setTag_string(tag_string);
        AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(admin_uuid);

        try {
            FileSaver fs = new FileSaver(file);
            String localPath = fsg.generator(fs);
            logger.info("localPath=" + localPath);
            String finalUrl = serverAbsolutePath + remoteService.processCommonFile(localPath, "questionnaire");
            QuestionnaireExcelParseTool excelParseTool = new QuestionnaireExcelParseTool();
            excelParseTool.setFilePath(localPath);
            Workbook workbook = excelParseTool.initWorkBook();
            if (workbook != null) {
                excelParseTool.parseWorkbook(workbook);
            }
            if (excelParseTool.invalid_method) {
                mResponseData.setCode(-1);
                mResponseData.setMsg("EXCEL第一行字段名称有错误，请不要修改模板中的第一行字段信息");
            } else {
                questionnaire.setFramework_id(adminUserInfoByUuid.getFramework_id());
                questionnaire.setCreate_by(adminUserInfoByUuid.getUuid());
                questionnaire.setCreate_date(new Date().getTime());
                questionnaire.setEnabled(1);
                questionnaire.setWaring_type(waring_type);
                tenantQuestionnairesService.insert(questionnaire);
                int maxNum = 0;
                if (excelParseTool.qns.size() > 0) {
                    for (int i = 0; i < excelParseTool.qns.size(); i++) {
                        QuestionnaireExcel excel = excelParseTool.qns.get(i);
                        TenantQuestionnaireQuestion qnQuestion = new TenantQuestionnaireQuestion();
                        qnQuestion.setQuestion(excel.getQuestion());
                        qnQuestion.setSort_code(i + 1);
                        qnQuestion.setQuestionnaire_id(questionnaire.getId());
                        tenantQuestionnaireQuestionService.insert(qnQuestion);
                        if (excel.getAnswers().size() > maxNum) {
                            maxNum = excel.getAnswers().size();
                        }
                        for (int j = 0; j < excel.getAnswers().size(); j++) {
                            AnswerExcel aExcel = excel.getAnswers().get(j);
                            TenantQuestionnaireAnswer qnAnswer = new TenantQuestionnaireAnswer();
                            qnAnswer.setAnswer(aExcel.getAnswer());
                            qnAnswer.setSort_code(j + 1);
                            qnAnswer.setScore(aExcel.getScore());
                            qnAnswer.setQuestion_id(qnQuestion.getId());
                            tenantQuestionnaireAnswerService.insert(qnAnswer);
                        }
                    }
                }
                questionnaire.setMax_answer(maxNum);
                questionnaire.setQuestion_sum(excelParseTool.qns.size());
                tenantQuestionnairesService.updateByPrimaryKeySelective(questionnaire);
                mResponseData.setMsg("添加问卷成功");
            }
        } catch (Exception e) {
            mResponseData.setCode(-1);
            mResponseData.setMsg("添加问卷失败");
            e.printStackTrace();
        }
        return mResponseData;
    }


    /**
     * 修改
     *
     * @param qn_id
     * @param questionnaire_description
     * @param waring_score
     * @param tag_string
     * @param admin_uuid
     * @param enabled                   1 有效 0 删除
     * @return
     */
    @RequestMapping("/updateQuestionnaire")
    @ResponseBody
    public ResponseData updateQuestionnaire(@RequestParam Long qn_id,
                                            String questionnaire_description, Double waring_score, String tag_string,
                                            @RequestParam(required = true) String admin_uuid, Integer enabled) {
        String opTime = new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date());
        ResponseData mResponseData = new ResponseData();

        if (qn_id == null) {
            mResponseData.setCode(-1);
            mResponseData.setMsg("问卷id为空");
            return mResponseData;
        }
        try {
            TenantQuestionnaires questionnaire = tenantQuestionnairesService.selectByPrimaryKey(qn_id);
            if (questionnaire == null) {
                mResponseData.setCode(-1);
                mResponseData.setMsg("问卷id错误");
                return mResponseData;
            }
            if (!StringUtils.isEmpty(questionnaire_description)) {
                questionnaire.setQuestionnaire_description(questionnaire_description);
            }
            if (waring_score != null)
                questionnaire.setWaring_score(waring_score);
            if (!StringUtils.isEmpty(tag_string))
                questionnaire.setTag_string(tag_string);
            if (enabled != null)
                questionnaire.setEnabled(enabled);
            tenantQuestionnairesService.updateByPrimaryKey(questionnaire);
        } catch (Exception e) {
            mResponseData.setMsg("失败");
            mResponseData.setCode(-1);
            e.printStackTrace();
        }

        return mResponseData;
    }

    /**
     * 问卷问题列表
     *
     * @param page
     * @param page_size
     * @param qn_id     问卷id
     * @return
     */
    @RequestMapping("/getqnQuestionList")
    @ResponseBody
    public ResponseData getqnQuestionList(Integer page, Integer page_size, @RequestParam(required = true) Long qn_id) {
        ResponseData mResponseData = new ResponseData();
        PageInfo pi = new PageInfo();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("questionnaire_id", qn_id);
        if (page != null && page_size != null) {
            pi.setCurrentPage(page);
            pi.setPageSize(page_size);
        }
        List<TenantQuestionnaireQuestion> list = tenantQuestionnaireQuestionService.listAllQnQuestions(pi, map);
        if (list != null && list.size() != 0) {
            for (int i = 0; i < list.size(); i++) {
                TenantQuestionnaireQuestion tenantQuestionnaireQuestion = list.get(i);
                List<TenantQuestionnaireAnswer> qnAnswerByQid = tenantQuestionnaireAnswerService.getQnAnswerByQid(tenantQuestionnaireQuestion.getId());
                if (qnAnswerByQid != null) {
                    tenantQuestionnaireQuestion.setQnAnswers(qnAnswerByQid);
                }
            }

        }
        Long count = tenantQuestionnaireQuestionService.listAllQnQuestionsCount(map);
        map.put("list", list);
        map.put("count", count);
        mResponseData.setData(map);
        return mResponseData;
    }


    /**
     * 问卷任务列表
     *
     * @param page
     * @param page_size
     * @param create_by    创建者
     * @param status       状态
     * @param framework_id
     * @param admin_uuid
     * @return
     */
    @RequestMapping("/getqnTaskList")
    @ResponseBody
    public ResponseData getqnTaskList(Integer page, Integer page_size, String create_by, Integer status,
                                      Long framework_id, @RequestParam(required = true) String admin_uuid, Long questionnaire_id) {
        PageInfo pi = new PageInfo();
        ResponseData mResponseData = new ResponseData();
        Map<String, Object> map = new HashMap<String, Object>();
        AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(admin_uuid);
        if (!StringUtils.isEmpty(create_by)) {
            map.put("create_by", create_by);
        } else {
            getTreePathDatas(framework_id, adminUserInfoByUuid, map);
//            getframeworkDatas(framework_id, adminUserInfoByUuid, map);
        }
        if (status != null)
            map.put("status", status);
        if (questionnaire_id != null)
            map.put("questionnaire_id", questionnaire_id);
        if (page != null && page_size != null) {
            pi.setCurrentPage(page);
            pi.setPageSize(page_size);
        }
        Integer count = tenantQuestionnaireTasksService.findAllQnTaskCount(map);
        List<TenantQuestionnaireTasks> list = tenantQuestionnaireTasksService.listAllQnTasks(pi, map);
        // 修改 tenant_questionnaire_tasks 中的user_num  Finish_num
//        Integer listSize = 0;
//        Map<String, Object> Newmap = new HashMap<>();
//        for (TenantQuestionnaireTasks tenantQuestionnaireTasks : list) {
//            Newmap.put("task_id", tenantQuestionnaireTasks.getId());
//            if (tenantQuestionnaireTasks.getUser_num() != null) {
//                Long userNum = eUserService.listQnTaskUsersCount(Newmap);
//                if (userNum.intValue() != tenantQuestionnaireTasks.getUser_num()) {
//                    tenantQuestionnaireTasks.setUser_num(userNum.intValue());
//                    tenantQuestionnaireTasksService.updateByPrimaryKey(tenantQuestionnaireTasks);
//                }
//                if (tenantQuestionnaireTasks.getFinish_num() != null) {
//                    int finishedCount = tenantQuestionnaireTaskInfoService.getUserQuestionnaireTaskInfoFinishedCount(Newmap);
//                    if (finishedCount != tenantQuestionnaireTasks.getFinish_num()) {
//                        tenantQuestionnaireTasks.setFinish_num(finishedCount);
//                        logger.info("---修改Finish_num-- 成功 Finish_num: " + finishedCount);
//                    }
//                    tenantQuestionnaireTasksService.updateByPrimaryKey(tenantQuestionnaireTasks);
//                }
//                list.set(listSize, tenantQuestionnaireTasks);
//            }
//
//            listSize++;
//        }
        map.clear();
        map.put("list", list);
        map.put("count", count);
        mResponseData.setData(map);
        return mResponseData;
    }

    /**
     * 删除问卷任务
     *
     * @param admin_uuid
     * @return
     */
    @RequestMapping("/deleteQnTaskList")
    @ResponseBody
    public ResponseData deleteQnTaskList(@RequestParam(required = true) Long task_id, @RequestParam(required = true) String admin_uuid) {
        PageInfo pi = new PageInfo();
        ResponseData mResponseData = new ResponseData();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(admin_uuid);
            TenantQuestionnaireTasks qntask = tenantQuestionnaireTasksService.selectByPrimaryKey(task_id);
            if (qntask == null) {
                mResponseData.setCode(-1);
                mResponseData.setMsg("无该任务记录");
            }
            qntask.setStatus(4);
            tenantQuestionnaireTasksService.updateByPrimaryKey(qntask);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return mResponseData;
    }

    /**
     * 新建问卷任务
     *
     * @param task_name     任务名
     * @param publish_date  时间
     * @param qn_ids        问卷ids
     * @param memo          描述
     * @param framework_ids 组织机构
     * @param addSon        是否添加下级
     * @param admin_uuid
     * @param user_uuids    用户ids
     * @return
     */
    @RequestMapping("/saveTask")
    @ResponseBody
    public ResponseData saveTask(String file, String task_name, Long publish_date, String qn_ids, String memo,
                                 String framework_ids, Integer addSon, @RequestParam(required = true) String admin_uuid, String user_uuids) {

        ResponseData mResponseData = new ResponseData();
        Map<String, Object> map = new HashMap<String, Object>();
        AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(admin_uuid);
        TenantQuestionnaireTasks task = saveTenantQuestionnaireTasks(task_name, publish_date, memo, map, adminUserInfoByUuid, qn_ids);

        ResponseData responseData = addTaskUsers(task.getId(), framework_ids, addSon, user_uuids, file, adminUserInfoByUuid.getChannel_id());
        if (responseData.getCode() == -1) return responseData;
        ResponseData responseData2 = submitTaskQns(task.getId(), qn_ids, adminUserInfoByUuid);
        map.put("id", task.getId());
        mResponseData.setData(map);
        return mResponseData;
    }

    private TenantQuestionnaireTasks saveTenantQuestionnaireTasks(String task_name, Long publish_date, String
            memo, Map<String, Object> map, AdminUser adminUserInfoByUuid, String qn_ids) {
        TenantQuestionnaireTasks task = new TenantQuestionnaireTasks();
        task.setName(task_name);
        task.setFramework_id(adminUserInfoByUuid.getFramework_id());
        task.setMemo(memo);
        // 随机获取任务图片
        Integer count = sysTaskImagesService.listPageTaskImagesCount(map);
        Random rand = new Random();
        Integer imageId = rand.nextInt(count) + 1;
        SysTaskImages taskImage = sysTaskImagesService.selectByPrimaryKey(imageId);
        if (taskImage != null) {
            task.setImage_url(taskImage.getImage_url());
        } else {
            List<SysTaskImages> list = sysTaskImagesService.listPageTaskImages(null, map);
            SysTaskImages taskImage2 = list.get(0);
            task.setImage_url(taskImage2.getImage_url());
        }
        task.setCreate_by(adminUserInfoByUuid.getUuid());
        task.setStatus(0);
        task.setQuestionnaire_ids(qn_ids);
        if (publish_date == null || publish_date == 0) {
            task.setPublish_date((new Date().getTime() / 1000) + 10);
        } else {
            task.setPublish_date(publish_date);
        }
        task.setCreate_date(new Date().getTime());
        tenantQuestionnaireTasksService.insert(task);
        return task;
    }


    /**
     * 添加问卷任务测评人员
     *
     * @param task_id
     * @param framework_ids
     * @param addSon        1  添加所有下属单位  0.仅添加本单位
     * @param user_uuids
     * @param file
     * @param channel_id
     * @return
     */
    public ResponseData addTaskUsers(Long task_id, String framework_ids, Integer addSon, String user_uuids, String file,
                                     String channel_id) {
        ResponseData mResponseData = new ResponseData();
        Map<String, Object> map = new HashMap<String, Object>();
        logger.info("+++++++++++++文件file=" + file);
        int count = 0;
        if (addSon == null) addSon = 0;
        List<Long> frameworkIds = new ArrayList<Long>();
        map.put("startTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        String prefix = "INSERT INTO tenant_questionnaire_task_info (task_id, user_uuid,task_status,enabled) VALUES ";
        List<String> mlist = new ArrayList<>();
        mlist.add("用户名");
        try {
            StringBuffer suffix = new StringBuffer();
            TenantQuestionnaireTasks qntask = tenantQuestionnaireTasksService.selectByPrimaryKey(task_id);
            if (file != null && !file.isEmpty()) {
                String localPath = file;
                logger.info("++++++++++++++++++++++++++文件=" + localPath + "++++++++++++++++++++++++++");
                UserExcelParseToolNew excelParseTool = new UserExcelParseToolNew();
                excelParseTool.setFilePath(localPath, mlist);
                org.apache.poi.ss.usermodel.Workbook workbook = excelParseTool.initWorkBook();
                if (workbook != null) {
                    excelParseTool.parseWorkbook(workbook);
                }
                if (!org.springframework.util.StringUtils.isEmpty(excelParseTool.errorMsg)) {
                    mResponseData.setCode(-1);
                    mResponseData.setMsg(excelParseTool.errorMsg);
                    return mResponseData;
                }
                if (excelParseTool.invalid_method) {
                    mResponseData.setCode(-1);
                    mResponseData.setMsg("EXCEL第一行字段名称有错误，请不要修改模板中的第一行字段信息");
                    return mResponseData;
                } else {
                    List<String> nameList = new ArrayList<>();
                    for (int i = 0; i < excelParseTool.mUserExcelList.size(); i++) {
                        logger.info("+++++++++++++姓名=" + excelParseTool.mUserExcelList.get(i).getUser_name());
                        nameList.add(excelParseTool.mUserExcelList.get(i).getUser_name());
                    }
                    map.put("UserNameList", nameList);
                    map.put("channel_id", channel_id);
                    List<String> userIDsByNameList = eUserService.getUserIDsByNameList(map);
                    if (userIDsByNameList == null || userIDsByNameList.size() == 0) {
                        mResponseData.setCode(-1);
                        mResponseData.setMsg("请检查用户名是否正确。");
                        return mResponseData;
                    } else {
                        for (int i = 0; i < userIDsByNameList.size(); i++) {
                            suffix.append("(" + task_id + ",'" + userIDsByNameList.get(i) + "'," + qntask.getStatus() + ", 1),");
                            count++;
                        }
                    }
                }
            } else if (framework_ids != null && !"".equals(framework_ids)) {
                String[] args = framework_ids.split(",");
                for (int i = 0; i < args.length; i++) {
                    Long aLong = Long.valueOf(args[i]);
                    if (!frameworkIds.contains(aLong)) {
                        frameworkIds.add(aLong);
                    }
                    if (addSon == 1) {
                        frameworkIds.addAll(getAllSonTenantFrameworksId(Long.getLong(args[i])));
                    }
                }
                Map<String, Object> p_map = new HashMap<String, Object>();
                p_map.put("framework_ids", frameworkIds);
                List<EUser> users = eUserService.listUsers(null,p_map);
                for (int j = 0; j < users.size(); j++) {
                    suffix.append("(" + task_id + ",'" + users.get(j).getUuid() + "'," + qntask.getStatus() + ", 1),");
                    count++;
                }
            } else if (user_uuids != null && !"".equals(user_uuids)) {
                String[] ids = user_uuids.split(",");
                for (int i = 0; i < ids.length; i++) {
                    suffix.append("(" + task_id + ",'" + ids[i] + "'," + qntask.getStatus() + ", 1),");
                    count++;
                }
            } else {
                mResponseData.setCode(-1);
                mResponseData.setMsg("请检查参数是否正确。");
                return mResponseData;
            }
            String sql = prefix + suffix.substring(0, suffix.length() - 1);
            jdbcTemplate.execute(sql);
            qntask.setUser_num(count);
            String framework_tree = "";
            String subtenant_tree = "";
            for (int i = 0; i < frameworkIds.size(); i++) {
                if (i == 0)
                    framework_tree += frameworkIds.get(i);
                else
                    framework_tree += "," + frameworkIds.get(i);
            }
            if ("".equals(framework_tree))
                qntask.setFramework_tree("");
            else
                qntask.setFramework_tree(framework_tree);
            tenantQuestionnaireTasksService.updateByPrimaryKey(qntask);
            // 头等连接

        } catch (Exception e) {
            e.printStackTrace();
            mResponseData.setCode(-1);
            mResponseData.setMsg("发生异常。");
            return mResponseData;
        }
        map.put("endTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        map.put("count", count);

        return mResponseData;
    }


    public ResponseData submitTaskQns(Long task_id, String qn_ids, AdminUser admin_user) {
        String opTime = new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date());
        ResponseData mResponseData = new ResponseData();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("startTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        TenantQuestionnaireTasks qntask = tenantQuestionnaireTasksService.selectByPrimaryKey(task_id);
        int count = 0;
        int task_status = 2;

        String prefix = "replace into tenant_questionnaire_task_info (id,task_id,user_uuid,questionnaire_id,finished,task_status,enabled) values ";
        try {
            // 保存sql后缀
            StringBuffer suffix = new StringBuffer();

            // 外层循环，总提交事务次数
            String[] args = qn_ids.split(",");
            for (int i = 0; i < args.length; i++) {
                Map<String, Object> p_map = new HashMap<>();
                p_map.put("task_id", task_id);
                List<TenantQuestionnaireTaskInfo> infos = tenantQuestionnaireTaskInfoService.listQnTaskInfoByMap(p_map);
                for (int j = 0; j < infos.size(); j++) {
                    TenantQuestionnaireTaskInfo info = infos.get(j);
                    if (i == 0)
                        suffix.append("(" + info.getId() + "," + task_id + ",'" + info.getUser_uuid() + "',"
                                + args[i] + ",0," + task_status + ", 1),");
                    else
                        suffix.append("(0," + task_id + ",'" + info.getUser_uuid() + "'," + args[i] + ",0,"
                                + task_status + ", 1),");
                    count++;
                }
            }
            String sql = prefix + suffix.substring(0, suffix.length() - 1);
            jdbcTemplate.execute(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // qn_ids = qn_ids.substring(0, qn_ids.length() -1 );
        qntask.setQuestionnaire_ids(qn_ids);
        qntask.setStatus(task_status);
        tenantQuestionnaireTasksService.updateByPrimaryKey(qntask);
        return mResponseData;
    }


    /**
     * 添加问卷任务测评人员
     *
     * @param task_id
     * @param framework_ids
     * @param addSon        1  添加所有下属单位  0.仅添加本单位
     * @param user_uuids
     * @return
     */
    @RequestMapping(value = "/addQnTaskUsers")
    @ResponseBody
    public ResponseData addQnTaskUsers(Long task_id, String framework_ids, Integer addSon, String user_uuids) {
        ResponseData mResponseData = new ResponseData();
        Map<String, Object> map = new HashMap<String, Object>();
        int count = 0;
        if (addSon == null) addSon = 0;
        List<Long> frameworkIds = new ArrayList<Long>();
        map.put("startTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        String prefix = "replace into tenant_questionnaire_task_info (task_id,user_uuid,questionnaire_id,finished,task_status,enabled) values ";
        try {
            // 保存sql后缀
            StringBuffer suffix = new StringBuffer();
            // 外层循环，总提交事务次数
            TenantQuestionnaireTasks qntask = tenantQuestionnaireTasksService.selectByPrimaryKey(task_id);
            String questionnaire_ids = qntask.getQuestionnaire_ids();
            String[] quids = questionnaire_ids.split(",");
            if (framework_ids != null && !"".equals(framework_ids)) {
                String[] args = framework_ids.split("\\|");
                for (int i = 0; i < args.length; i++) {
                    if (!frameworkIds.contains(Long.getLong(args[i]))) {
                        frameworkIds.add(Long.getLong(args[i]));
                    }
                    if (addSon == 1) {
                        frameworkIds.addAll(getAllSonTenantFrameworksId(Long.getLong(args[i])));
                    }
                }
                Map<String, Object> p_map = new HashMap<String, Object>();
                p_map.put("framework_ids", frameworkIds);
                List<EUser> users = eUserService.listUsers(null,p_map);
                for (int i = 0; i < quids.length; i++) {
                    for (int j = 0; j < users.size(); j++) {
                        Map<String, Object> mapTemp = new HashMap<String, Object>();
                        mapTemp.put("task_id", task_id);
                        mapTemp.put("questionnaire_id", quids[i]);
                        mapTemp.put("user_uuid", users.get(j).getUuid());
                        List<TenantQuestionnaireTaskInfo> tenantQuestionnaireTaskInfos = tenantQuestionnaireTaskInfoService.listQnTaskInfoByMap(mapTemp);
                        if (tenantQuestionnaireTaskInfos == null || tenantQuestionnaireTaskInfos.size() == 0) {
                            suffix.append("(" + task_id + ",'" + users.get(j).getUuid() + "'," + quids[i] + ",0," + qntask.getStatus() + ", 1),");
                            count++;
                        }
                    }
                }
                if (quids.length != 0) count = count / quids.length;
            } else {
                for (int i = 0; i < quids.length; i++) {
                    if (user_uuids != null && !"".equals(user_uuids)) {
                        String[] ids = user_uuids.split(",");

                        for (int j = 0; j < ids.length; j++) {
                            Map<String, Object> mapTemp = new HashMap<String, Object>();
                            mapTemp.put("task_id", task_id);
                            mapTemp.put("questionnaire_id", quids[i]);
                            mapTemp.put("user_uuid", ids[j]);
                            List<TenantQuestionnaireTaskInfo> tenantQuestionnaireTaskInfos = tenantQuestionnaireTaskInfoService.listQnTaskInfoByMap(mapTemp);
                            if (tenantQuestionnaireTaskInfos == null || tenantQuestionnaireTaskInfos.size() == 0) {
                                suffix.append("(" + task_id + ",'" + ids[j] + "'," + quids[i] + ",0," + qntask.getStatus() + ", 1),");
                                count++;
                            }
                        }
                    }
                }
                if (quids.length != 0) count = count / quids.length;
            }
            if (suffix.length() < 1) {
                mResponseData.setCode(-1);
                mResponseData.setMsg("添加失败");
                return mResponseData;
            }
            String sql = prefix + suffix.substring(0, suffix.length() - 1);
            jdbcTemplate.execute(sql);
            Integer user_num = qntask.getUser_num();
            qntask.setUser_num(user_num + count);
            String framework_tree = "";
            String subtenant_tree = "";
            for (int i = 0; i < frameworkIds.size(); i++) {
                if (i == 0)
                    framework_tree += frameworkIds.get(i);
                else
                    framework_tree += "," + frameworkIds.get(i);
            }
            if ("".equals(framework_tree))
                qntask.setFramework_tree("");
            else
                qntask.setFramework_tree(framework_tree);
            tenantQuestionnaireTasksService.updateByPrimaryKey(qntask);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return mResponseData;
    }

    /**
     * 删除任务测评人员
     *
     * @return
     */
    @RequestMapping("/deteleTaskUsers")
    @ResponseBody
    public ResponseData deleteTaskUsers(Long task_id, String user_uuids, String admin_uuid) {
        String opTime = new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date());
        ResponseData mResponseData = new ResponseData();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("startTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        int count = 0;
        List<String> frameworks = new ArrayList<String>();
        List<String> subtenants = new ArrayList<String>();
        TenantQuestionnaireTasks qntask = tenantQuestionnaireTasksService.selectByPrimaryKey(task_id);
        if (user_uuids != null && !"".equals(user_uuids)) {
            String[] ids = user_uuids.split(",");
            for (int i = 0; i < ids.length; i++) {
                Map<String, Object> para_map = new HashMap<String, Object>();
                para_map.put("task_id", task_id);
                para_map.put("user_uuid", ids[i]);
                int i1 = tenantQuestionnaireTaskInfoService.deleteQnTaskInfo(para_map);
                if (i1 != 0)
                    count++;
            }
        }
        if (qntask.getUser_num() != null)
            qntask.setUser_num(qntask.getUser_num() - count);
        String framework_tree = "";
        String subtenant_tree = "";
        for (int i = 0; i < frameworks.size(); i++) {
            if (i == 0)
                framework_tree += frameworks.get(i);
            else
                framework_tree += "," + frameworks.get(i);
        }

        if ("".equals(framework_tree))
            qntask.setFramework_tree("");
        else
            qntask.setFramework_tree(framework_tree);
        tenantQuestionnaireTasksService.updateByPrimaryKey(qntask);
        map.put("endTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        map.put("count", count);
        mResponseData.setData(map);
        return mResponseData;
    }


    /**
     * 用户查看当前任务
     *
     * @param request
     * @param user_uuid 用户id
     * @param page
     * @param page_size
     * @param type      0 未完成  1 已完成
     * @return
     */
    @RequestMapping("/userTasks")
    @ResponseBody
    public ResponseData userTasks(HttpServletRequest request, String user_uuid, Integer page, Integer page_size, Integer type) {
        ResponseData mResponseData = new ResponseData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<TenantQuestionnaireTasks> tasks = new ArrayList<TenantQuestionnaireTasks>();
        map.put("user_uuid", user_uuid);
        if (type == 0)
            map.put("unfinished", 1);
        else if (type == 1)
            map.put("finished", 1);
        PageInfo pi = new PageInfo();
        pi.setCurrentPage(page);
        pi.setPageSize(page_size);
        try {
            List<Map<String, Object>> info_maps = tenantQuestionnaireTaskInfoService.listPageQnTaskInfos(pi, map);
            for (int i = 0; i < info_maps.size(); i++) {
                Map<String, Object> info_map = info_maps.get(i);
                TenantQuestionnaireTasks task = tenantQuestionnaireTasksService.selectByPrimaryKey((Long) info_map.get("task_id"));
                task.setPercentage(String.valueOf(((BigDecimal) info_map.get("percentage")).intValue()));
                Map<String, Object> userParam = new HashMap<>();
                AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(task.getCreate_by());
                if (adminUserInfoByUuid == null) { // 专业账号删除后或者测试账号失效后无法搜索出来
                    task.setCreate_name("无效账号");
                } else {
                    task.setCreate_name(adminUserInfoByUuid.getReal_name());
                }
                tasks.add(task);
            }
            Map<String, Object> attr = new HashMap<String, Object>();
            attr.put("count", tenantQuestionnaireTaskInfoService.listPageQnTaskInfosCount(map));
            attr.put("list", tasks);
            mResponseData.setData(attr);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            mResponseData.setCode(-1);
            mResponseData.setMsg(e.getMessage());
        }

        return mResponseData;
    }

    /**
     * 用户查看当前任务的具体量表
     *
     * @return
     * @throws
     */
    @RequestMapping("/userTaskTests")
    @ResponseBody
    public ResponseData userTaskTests(HttpServletRequest request, String user_uuid, Long task_id) {
        String opTime = new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date());
        ResponseData mResponseData = new ResponseData();
        Map<String, Object> map = new HashMap<String, Object>();
        List<TenantQuestionnaireTaskInfo> taskInfos = new ArrayList<TenantQuestionnaireTaskInfo>();
        map.put("user_uuid", user_uuid);
        map.put("task_id", task_id);
        try {
            taskInfos = tenantQuestionnaireTaskInfoService.listAllQnTaskInfos(map);
            int finish_count = 0;
            for (int i = 0; i < taskInfos.size(); i++) {
                TenantQuestionnaireTaskInfo info = taskInfos.get(i);
                if (info.getFinished() == 1) {
                    taskInfos.get(i).setAnswered_sum(info.getQuestion_sum());
                    finish_count++;
                } else if (info.getAnswer() == null || "".equals(info.getAnswer()))
                    taskInfos.get(i).setAnswered_sum(0);
                else {
                    String[] args = info.getAnswer().split("\\|");
                    taskInfos.get(i).setAnswered_sum(args.length);
                }
            }
            Map<String, Object> attr = new HashMap<>();
            TenantQuestionnaireTasks task = tenantQuestionnaireTasksService.selectByPrimaryKey(task_id);
            task.setPercentage(String.valueOf(finish_count * 100 / taskInfos.size()));
            AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(task.getCreate_by());
            if (adminUserInfoByUuid == null) { // 专业账号删除后或者测试账号失效后无法搜索出来
                task.setCreate_name("无效账号");
            } else {
                task.setCreate_name(adminUserInfoByUuid.getReal_name());
            }
            attr.put("task", task);
            attr.put("taskInfos", taskInfos);
            mResponseData.setData(attr);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            mResponseData.setCode(-1);
            mResponseData.setMsg(e.getMessage());
        }

        return mResponseData;
    }

    /**
     * 获取量表所有题目和选项
     *
     * @param
     * @return
     */
    @RequestMapping("/getTableAllInfos")
    @ResponseBody
    public ResponseData getTableAllInfos(Long qtask_info_id) {
        ResponseData mResponseData = new ResponseData();
        Map<String, Object> map = new HashMap<String, Object>();
        TableAllInfo mTableAllInfo = new TableAllInfo();
        String mAnswerStr = "";
        try {
            TenantQuestionnaireTaskInfo info = tenantQuestionnaireTaskInfoService.selectByPrimaryKey(qtask_info_id);
            if (info == null) {
                mResponseData.setMsg("ID错误");
                mResponseData.setCode(-1);
                return mResponseData;
            }
            mAnswerStr = info.getAnswer();
            List<Map<String, Object>> mTableAllInfos = mSysTestingQuestionService.findQuestionnaireAllInfosByTableUuid(info.getQuestionnaire_id() + "");
            List<QuestionInfos> qtList = new ArrayList();
            List<String> sortList = new ArrayList();
            if (mTableAllInfos != null && mTableAllInfos.size() != 0) {
                for (int i = 0; i < mTableAllInfos.size(); i++) {
                    mTableAllInfo.setDescription(mTableAllInfos.get(i).get("questionnaire_description") + "");
                    mTableAllInfo.setUuid(mTableAllInfos.get(i).get("qnid").toString());
                    if (!sortList.contains(mTableAllInfos.get(i).get("qusort").toString())) {
                        sortList.add(mTableAllInfos.get(i).get("qusort").toString());
                        QuestionInfos mQuestionInfos = new QuestionInfos();
                        mQuestionInfos.setQuestionTitle(mTableAllInfos.get(i).get("question").toString());
                        qtList.add(mQuestionInfos);
                    }
                }
            }
            List<QuestionInfos> mquestionList = new ArrayList();
            for (int i = 0; i < sortList.size(); i++) {
                QuestionInfos mQuestionInfo = new QuestionInfos();
                List<QuestionAnswersInfos> anList = new ArrayList();
                mQuestionInfo = qtList.get(i);
                for (int k = 0; k < mTableAllInfos.size(); k++) {
                    if (sortList.get(i).equals(mTableAllInfos.get(k).get("qusort").toString())) {
                        QuestionAnswersInfos mQuestionAnswersInfos = new QuestionAnswersInfos();
                        mQuestionAnswersInfos.setAnswers(mTableAllInfos.get(k).get("answer").toString());
                        anList.add(mQuestionAnswersInfos);
                    }
                }
                mQuestionInfo.setAnswers(anList);
                mquestionList.add(mQuestionInfo);
            }
            mTableAllInfo.setQuestionInfos(mquestionList);
            map.put("mTableAllInfo", mTableAllInfo);
            map.put("mAnswerStr", mAnswerStr);
            mResponseData.setData(map);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            mResponseData.setCode(-1);
            return mResponseData;
        }
        return mResponseData;
    }

    /**
     * 用户做量表
     *
     * @return
     * @throws
     */
    @RequestMapping("/handleQuestion")
    @ResponseBody
    public ResponseData handleQuestion(Long qtask_info_id, String user_uuid,
                                       Integer index, String value, String times) {
        ResponseData mResponseData = new ResponseData();
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> Qnmap = new HashMap<String, Object>();
        TenantQuestionnaireTaskInfo info = tenantQuestionnaireTaskInfoService.selectByPrimaryKey(qtask_info_id);
        TenantQuestionnaires table = tenantQuestionnairesService.findQuestionnaireById(info.getQuestionnaire_id());

        boolean isLast = false;
        String answer = info.getAnswer();
        String answer_seconds = info.getAnswer_seconds();
        Integer count = 0;

        if (value == null || value.equals("")) {
            map.put("answer", answer);
            map.put("answer_seconds", answer_seconds);
            mResponseData.setData(map);
            return mResponseData;
        } else {
            if (value.contains("|")) {
                count = value.split("\\|").length - 1;
            } else {
                count = 0;
            }

            if ((index + count) - table.getQuestion_sum() > 0) {
                map.put("answer", answer);
                mResponseData.setCode(-1);
                mResponseData.setMsg("答题数据重复提交");
                mResponseData.setData(map);
                return mResponseData;
            }

            // 特殊字符处理
            value.replace("&", "");
            value.replace("@", "");
            value.replace("，", ",");
            if (index == 1 || answer == null || "".equals(answer)) {
                info.setAnswer(value);
                info.setAnswer_seconds(times);
            } else {
                String[] arg = answer.split("\\|");
                String[] manswerSeconds = answer_seconds.split("\\|");
                if (arg.length == index - 1) {
                    info.setAnswer(info.getAnswer() + "|" + value);
                    info.setAnswer_seconds(info.getAnswer_seconds() + "|" + times);
                } else if (arg.length > index - 1) {
                    String jion = "";
                    String answerSeconds = "";
                    for (int i = 0; i < index - 1; i++) {
                        if (i == 0) {
                            jion = arg[i];
                            answerSeconds = manswerSeconds[i];
                        } else {
                            jion += "|" + arg[i];
                            answerSeconds += "|" + manswerSeconds[i];
                        }

                    }
                    info.setAnswer(jion + "|" + value);
                    info.setAnswer_seconds(answerSeconds + "|" + times);
                } else if (arg.length < index - 1) {
                    map.put("answer", answer);

                    mResponseData.setCode(-1);
                    mResponseData.setMsg("部分答题数据丢失");
                    mResponseData.setData(map);
                    return mResponseData;
                }

            }

            if ((index + count) - table.getQuestion_sum() == 0) {
                isLast = true;
                info.setFinished(1);
                String seconds = info.getAnswer_seconds();
                Integer time = 0;
                if (seconds.contains("|")) {
                    String[] mSeconds = seconds.split("\\|");
                    for (int i = 0; i < mSeconds.length; i++) {
                        time += Integer.parseInt(mSeconds[i]);
                    }
                } else {
                    time = Integer.parseInt(seconds);
                }

                info.setAnswer_time(time);

            }
            tenantQuestionnaireTaskInfoService.updateByPrimaryKeySelective(info);
        }
        if (isLast) {
            /*Integer answer_time = info.getAnswer_time();
            String[] split = info.getAnswer().split("\\|");
            Integer time = (split.length + 1) * 2;
            if (answer_time < time) {
                mResponseData.setCode(-2);
                mResponseData.setMsg("答题不可信,请重新作答!");
                info.setAnswer("");
                info.setAnswer_seconds("");
                info.setAnswer_time(0);
                tenantQuestionnaireTaskInfoService.updateByPrimaryKeySelective(info);
                return mResponseData;
            }
            List<String> ss = new ArrayList<String>();
            for (String sss : info.getAnswer().replaceAll("[^0-9]", ",").split(",")) {
                if (sss.length() > 0)
                    ss.add(sss);
            }
            List<String> collect = ss.stream().distinct().collect(Collectors.toList());
            if (collect != null && collect.size() == 1) {
                if (!collect.contains(1)) {
                    mResponseData.setCode(-2);
                    mResponseData.setMsg("答题不可信,请重新作答!");
                    info.setAnswer("");
                    info.setAnswer_seconds("");
                    info.setAnswer_time(0);
                    tenantQuestionnaireTaskInfoService.updateByPrimaryKeySelective(info);
                    return mResponseData;
                }
            }*/

            map.put("answer", "");
            Map<String, Object> map2 = new HashMap<String, Object>();
            map2.put("task_id", info.getTask_id());
            map2.put("user_uuid", info.getUser_uuid());
            TenantQuestionnaireTaskInfo finish_info = tenantQuestionnaireTaskInfoService.findFinishedQnTask(map2);

            if (finish_info != null) {
                TenantQuestionnaireTasks task = tenantQuestionnaireTasksService.selectByPrimaryKey(info.getTask_id());
                Map<String, Object> pmap = new HashMap<String, Object>();
                pmap.put("task_id", task.getId());
                Long userCount = eUserService.listQnTaskUsersCount(pmap);
                int finishedCount = tenantQuestionnaireTaskInfoService.getUserQuestionnaireTaskInfoFinishedCount(pmap);
                if (task.getUser_num() != null) {
                    if (userCount.intValue() != task.getUser_num()) {
                        task.setUser_num(userCount.intValue());
                        logger.info("---修改User_num-- 成功 User_num: " + userCount.intValue());
                    }
                    if (task.getFinish_num()==null || finishedCount != task.getFinish_num()) {
                        task.setFinish_num(finishedCount);
                        logger.info("---修改Finish_num-- 成功 Finish_num: " + finishedCount);
                    }
                    if (task.getUser_num() != 0 && task.getFinish_num() == task.getUser_num()) {// 所有人员完成问卷
                        task.setStatus(3);
                    }
                    tenantQuestionnaireTasksService.updateByPrimaryKey(task);
                }
            }
            String[] allAnswers = info.getAnswer().split("\\|");
            List<Map<String, Object>> scoreListMap = tenantQuestionnaireAnswerService.getScoreByQnId(table.getId());
            int score = 0;
            if (table.getWaring_type() != null) {
                for (int i = 0; i < allAnswers.length; i++) {
                    for (int j = 0; j < scoreListMap.size(); j++) {
                        if ((int) scoreListMap.get(j).get("qnsort") == i + 1) {
                            if (allAnswers[i].contains(",")) {
                                score += 0;
                            } else if ((int) scoreListMap.get(j).get("ansort") == Integer.parseInt(allAnswers[i])) {
                                score += (int) scoreListMap.get(j).get("score");
                            }
                        }
                    }
                }
                if (table.getWaring_type() == 1) {
                    if (score >= table.getWaring_score()) {
                        info.setWaring_result(1);
                    } else {
                        info.setWaring_result(2);
                    }
                }
                if (table.getWaring_type() == 2) {
                    if (score <= table.getWaring_score()) {
                        info.setWaring_result(1);
                    } else {
                        info.setWaring_result(2);
                    }
                }
            }
            info.setScore(score);
            map.put("score", score);
            map.put("tag_string", table.getTag_string());
            tenantQuestionnaireTaskInfoService.updateByPrimaryKeySelective(info);

        }
        mResponseData.setData(map);
        return mResponseData;
    }

    /**
     * 用户做量表
     *
     * @return
     * @throws
     */
    @RequestMapping("/handleQuestionnew")
    @ResponseBody
    public ResponseData handleQuestionnew(Long qtask_info_id, String value, String times) {
        ResponseData mResponseData = new ResponseData();
        Map<String, Object> map = new HashMap<>();
        TenantQuestionnaireTaskInfo info = tenantQuestionnaireTaskInfoService.selectByPrimaryKey(qtask_info_id);
        TenantQuestionnaires table = tenantQuestionnairesService.findQuestionnaireById(info.getQuestionnaire_id());

        boolean isLast = false;
        String answer = info.getAnswer();
        String answer_seconds = info.getAnswer_seconds();
        Integer count;

        if (value == null || value.equals("")) {
            map.put("answer", answer);
            map.put("answer_seconds", answer_seconds);
            mResponseData.setData(map);
            return mResponseData;
        } else {
            if (value.contains("|")) {
                count = value.split("\\|").length - 1;
            } else {
                count = 0;
            }
            // 特殊字符处理
            value.replace("&", "");
            value.replace("@", "");
            value.replace("，", ",");
            info.setAnswer(value);
            info.setAnswer_seconds(times);

            if ((count) - table.getQuestion_sum() == 0) {
                isLast = true;
                info.setFinished(1);
                String seconds = info.getAnswer_seconds();
                Integer time = 0;
                if (seconds.contains("|")) {
                    String[] mSeconds = seconds.split("\\|");
                    for (int i = 0; i < mSeconds.length; i++) {
                        time += Integer.parseInt(mSeconds[i]);
                    }
                } else {
                    time = Integer.parseInt(seconds);
                }
                info.setAnswer_time(time);

            }
            tenantQuestionnaireTaskInfoService.updateByPrimaryKeySelective(info);
        }
        if (isLast) {
            /*Integer answer_time = info.getAnswer_time();
            String[] split = info.getAnswer().split("\\|");
            Integer time = (split.length + 1) * 2;
            if (answer_time < time) {
                mResponseData.setCode(-2);
                mResponseData.setMsg("答题不可信,请重新作答!");
                info.setAnswer("");
                info.setAnswer_seconds("");
                info.setAnswer_time(0);
                tenantQuestionnaireTaskInfoService.updateByPrimaryKeySelective(info);
                return mResponseData;
            }
            List<String> ss = new ArrayList<String>();
            for (String sss : info.getAnswer().replaceAll("[^0-9]", ",").split(",")) {
                if (sss.length() > 0)
                    ss.add(sss);
            }
            List<String> collect = ss.stream().distinct().collect(Collectors.toList());
            if (collect != null && collect.size() == 1) {
                if (!collect.contains(1)) {
                    mResponseData.setCode(-2);
                    mResponseData.setMsg("答题不可信,请重新作答!");
                    info.setAnswer("");
                    info.setAnswer_seconds("");
                    info.setAnswer_time(0);
                    tenantQuestionnaireTaskInfoService.updateByPrimaryKeySelective(info);
                    return mResponseData;
                }
            }*/

            map.put("answer", "");
            Map<String, Object> map2 = new HashMap<String, Object>();
            map2.put("task_id", info.getTask_id());
            map2.put("user_uuid", info.getUser_uuid());
            TenantQuestionnaireTaskInfo finish_info = tenantQuestionnaireTaskInfoService.findFinishedQnTask(map2);

            if (finish_info != null) {
                TenantQuestionnaireTasks task = tenantQuestionnaireTasksService.selectByPrimaryKey(info.getTask_id());
                Map<String, Object> pmap = new HashMap<String, Object>();
                pmap.put("task_id", task.getId());
                Long userCount = eUserService.listQnTaskUsersCount(pmap);
                int finishedCount = tenantQuestionnaireTaskInfoService.getUserQuestionnaireTaskInfoFinishedCount(pmap);
                if (task.getUser_num() != null) {
                    if (userCount.intValue() != task.getUser_num()) {
                        task.setUser_num(userCount.intValue());
                        logger.info("---修改User_num-- 成功 User_num: " + userCount.intValue());
                    }
                    if (task.getFinish_num()==null || finishedCount != task.getFinish_num()) {
                        task.setFinish_num(finishedCount);
                        logger.info("---修改Finish_num-- 成功 Finish_num: " + finishedCount);
                    }
                    if (task.getUser_num() != 0 && task.getFinish_num() == task.getUser_num()) {// 所有人员完成问卷
                        task.setStatus(3);
                    }
                    tenantQuestionnaireTasksService.updateByPrimaryKey(task);
                }
            }
            String[] allAnswers = info.getAnswer().split("\\|");
            List<Map<String, Object>> scoreListMap = tenantQuestionnaireAnswerService.getScoreByQnId(table.getId());
            int score = 0;
            if (table.getWaring_type() != null) {
                for (int i = 0; i < allAnswers.length; i++) {
                    for (int j = 0; j < scoreListMap.size(); j++) {
                        if ((int) scoreListMap.get(j).get("qnsort") == i + 1) {
                            if (allAnswers[i].contains(",")) {
                                score += 0;
                            } else if ((int) scoreListMap.get(j).get("ansort") == Integer.parseInt(allAnswers[i])) {
                                score += (int) scoreListMap.get(j).get("score");
                            }
                        }
                    }
                }
                if (table.getWaring_type() == 1) {
                    if (score >= table.getWaring_score()) {
                        info.setWaring_result(1);
                    } else {
                        info.setWaring_result(2);
                    }
                }
                if (table.getWaring_type() == 2) {
                    if (score <= table.getWaring_score()) {
                        info.setWaring_result(1);
                    } else {
                        info.setWaring_result(2);
                    }
                }
            }
            info.setScore(score);
            map.put("score", score);
            map.put("tag_string", table.getTag_string());
            tenantQuestionnaireTaskInfoService.updateByPrimaryKeySelective(info);

        }
        mResponseData.setData(map);
        return mResponseData;
    }

    /**
     * 用户已完成问卷列表
     *
     * @param framework_id
     * @param waring_result    预警1 正常2 不预警0
     * @param admin_uuid
     * @param user_name
     * @param real_name
     * @param user_gender
     * @param test_begin_date
     * @param test_end_date
     * @param questionnaire_id
     * @param task_id
     * @param user_uuid
     * @return
     */
    @RequestMapping("/listFinishUserAndTaskInfo")
    @ResponseBody
    public ResponseData listFinishUserAndTaskInfo(Integer page, Integer page_size, Long framework_id,
                                                  Integer waring_result, String admin_uuid,
                                                  String user_name, String real_name, String user_gender,
                                                  String test_begin_date, String test_end_date,
                                                  Integer minScore, Integer maxScore,
                                                  Long questionnaire_id, Long task_id,
                                                  String user_uuid) {
        ResponseData mResponseData = new ResponseData();
        Map<String, Object> map = new HashMap<String, Object>();

        AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(admin_uuid);
//        getframeworkDatas(framework_id, adminUserInfoByUuid, map);
        getTreePathDatas(framework_id, adminUserInfoByUuid, map);
        if (waring_result != null)
            map.put("waring_result", waring_result);
        if (questionnaire_id != null)
            map.put("questionnaire_id", questionnaire_id);
        if (task_id != null)
            map.put("task_id", task_id);
        if (minScore != null)
            map.put("minScore", minScore);
        if (maxScore != null)
            map.put("maxScore", maxScore);
        if (!StringUtils.isEmpty(user_name))
            map.put("user_name", user_name);
            map.put("searchName", user_name);
        if (!StringUtils.isEmpty(real_name))
            map.put("real_name", real_name);
        if (!StringUtils.isEmpty(user_gender))
            map.put("user_gender", user_gender);
        if (!StringUtils.isEmpty(test_begin_date))
            map.put("test_begin_date", test_begin_date);
        if (!StringUtils.isEmpty(test_end_date))
            map.put("test_end_date", test_end_date);
        if (!StringUtils.isEmpty(user_uuid))
            map.put("user_uuid", user_uuid);
        PageInfo pi = null;
        if (page != null && page_size != null) {
            pi = new PageInfo();
            pi.setCurrentPage(page);
            pi.setPageSize(page_size);
        }
      //  List<Map<String, Object>> listQuestionName = tenantQuestionnairesService.listAllTenantQuestionnaires(null);
        List<Map<String, Object>> mapList = tenantQuestionnaireTaskInfoService.listFinishUserAndTaskInfo(pi, map);
        long count = tenantQuestionnaireTaskInfoService.listFinishUserAndTaskInfoCount(map);
        map.clear();
        map.put("list", mapList);
        map.put("count", count);
       // map.put("listQuestionName",listQuestionName);
        mResponseData.setData(map);
        return mResponseData;
    }

    /**
     * 问卷任务详情页问卷列表
     *
     * @param dataGrid
     * @param id
     * @return
     */
    @RequestMapping("/questionnaireDatagrid")
    @ResponseBody
    public DataGrid questionnaireDatagrid(HttpServletRequest request, DataGrid dataGrid, Long id, String
            user_id) {
        String opTime = new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date());
        PageInfo pi = new PageInfo();
        Map<String, Object> map = new HashMap<String, Object>();
        TenantUsers user = getUserInfoById(user_id);
        TenantQuestionnaireTasks task = tenantQuestionnaireTasksService.selectByPrimaryKey(id);
        String[] tableUuids = task.getQuestionnaire_ids().split(";");
//        getCustom(request,user);
        boolean isCustomTable = (boolean) request.getSession().getAttribute("is_custom_table");
        map.put("is_custom_table", isCustomTable);
        map.put("ids", tableUuids);
        if (dataGrid.getPage() > 0) {
            pi.setCurrentPage(dataGrid.getPage());
            // pi.setPageSize(Integer.parseInt(dataGrid.getRows().get(0).toString()));
        }
        Long count = tenantQuestionnairesService.findQnTaskQuestionnairesCount(map);
        pi.setPageSize(count.intValue());
        List<TenantQuestionnaires> list = tenantQuestionnairesService.findQnTaskQuestionnaires(pi, map);
        dataGrid.setRows(list);
        dataGrid.setTotal(count);

        return dataGrid;
    }


    /**
     * 导出问卷任务未完成人员
     * http://192.168.0.197:8094/cloud-customer/questionnaire/exUndoneUser?task_id=123
     *
     * @param task_id
     * @param
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/exUndoneUser")
    public String exUndoneUser(String task_id, HttpServletResponse response, String admin_uuid) throws IOException {
        String fileName = "问卷任务未完成人员";
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        // 根据传进来的file对象创建可写入的Excel工作薄
        OutputStream os = response.getOutputStream();
        try {
            WritableWorkbook wwb = null;
            // 创建可写入的Excel工作簿
            wwb = jxl.Workbook.createWorkbook(os);
            WritableSheet ws = wwb.createSheet("问卷任务未完成人员信息表", 0);
            // 查询数据库中所有的数据
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("task_id", task_id);
            map.put("finished", 0);
            //  EUser userInfoByUuid = getUserInfoByUuid(admin_uuid);
            List<EUser> list = eUserService.listQnTaskUsers(map);
            for (EUser entity : list) {
                TenantFrameworks fra = tenantFrameworksService.getFrameworkById(entity.getFramework_id());
                if (fra != null) {
                    String whole_Name = fra.getWhole_name();
                    entity.setFramework_name(whole_Name);
                }
            }
            // 要插入到的Excel表格的行号，默认从0开始
            Label real_name = new Label(0, 0, "真实姓名");
            Label frame_work = new Label(1, 0, "组织机构");
            ws.addCell(real_name);
            ws.addCell(frame_work);
            // 组织机构
            for (int i = 0; i < list.size(); i++) {
                Label real_name_i = new Label(0, i + 1, list.get(i).getReal_name() + "");
                Label frame_work_i = new Label(1, i + 1, list.get(i).getWhole_name() + "");
                ws.addCell(real_name_i);
                ws.addCell(frame_work_i);
            }
            // 写进文档
            wwb.write();
            // // System.out.println("Excel导出成功！");
            // 关闭Excel工作簿对象
            wwb.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                os.close();
            }
        }

        return null;
    }

    @RequestMapping("/showTaskDetail")
    @ResponseBody
    public ResponseData showTaskDetail(Long task_id) {
        Map<String, Object> map = new HashMap<String, Object>();
        ResponseData mResponseData = new ResponseData();
        if (task_id == null) {
            mResponseData.setCode(-1);
            mResponseData.setMsg("task_id不能为空");
            return mResponseData;
        }
        map.put("task_id", task_id);
        List<TenantQuestionnaireTasks> tenantQuestionnaireTasks = tenantQuestionnaireTasksService.listAllQnTasks(null, map);

        if (tenantQuestionnaireTasks == null || tenantQuestionnaireTasks.size() == 0) {
            mResponseData.setCode(-1);
            mResponseData.setMsg("无该问卷信息");
            return mResponseData;
        }
        String questionnaire_ids = tenantQuestionnaireTasks.get(0).getQuestionnaire_ids();
        List<TenantQuestionnaires> mTenantQuestionnaires = new ArrayList<>();
        long qnTaskQuestionnairesCount = 0;
        if (questionnaire_ids != null) {
            String[] split = questionnaire_ids.split(",");
            List<String> list = Arrays.asList(split);
            map.put("ids", list);
            mTenantQuestionnaires = tenantQuestionnairesService.findQnTaskQuestionnaires(null, map);
            qnTaskQuestionnairesCount = tenantQuestionnairesService.findQnTaskQuestionnairesCount(map);
        }
        map.clear();
        map.put("tenantTableTasks", tenantQuestionnaireTasks);
        map.put("list", mTenantQuestionnaires);
        map.put("count", qnTaskQuestionnairesCount);
        mResponseData.setData(map);
        return mResponseData;
    }

    /**
     * 问卷任务用户
     *
     * @param task_id
     * @return
     */
    @RequestMapping("/getUserByTaskid")
    @ResponseBody
    public ResponseData getUserByTaskid(Integer page, Integer page_size, String task_id) {
        ResponseData mResponseData = new ResponseData();
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isEmpty(task_id)) {
            mResponseData.setCode(-1);
            mResponseData.setMsg("任务id为空");
            return mResponseData;
        }
        map.put("task_id", task_id);
        PageInfo pi = new PageInfo();
        if (page != null && page_size != null) {
            pi.setCurrentPage(page);
            pi.setPageSize(page_size);
        }
        try {
            Long count = eUserService.listQnTaskUsersCount(map);
            List<EUser> list = eUserService.listQnTaskUsers(PageInfoParams.buildMap(pi, map));
            map.clear();
            map.put("list", list);
            map.put("count", count);
            mResponseData.setData(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mResponseData;
    }


    /**
     * 问卷选项统计
     *
     * @param qtask_id 任务id
     * @return
     */
    @RequestMapping("/qnAnswerCensus")
    @ResponseBody
    public ResponseData qnAnswerCensus(Long qtask_id) {
        ResponseData mResponseData = new ResponseData();
        List<Object> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        try {
            TenantQuestionnaireTasks task = tenantQuestionnaireTasksService.selectByPrimaryKey(qtask_id);
            String[] qn_ids = task.getQuestionnaire_ids().split(","); // 任务中有多个问卷
            for (int index = 0; index < qn_ids.length; index++) {
                Map<String, Object> mapT = new HashMap<>();
                Long qn_id = Long.valueOf(qn_ids[index]);
                List<TenantQuestionnaireQuestion> questions = tenantQuestionnaireQuestionService.listQnQuestionAllList(qn_id);
                List<QnCensus> censuses = new ArrayList<QnCensus>();
                for (int i = 0; i < questions.size(); i++) {
                    QnCensus census = new QnCensus();
                    TenantQuestionnaireQuestion question = questions.get(i);
                    census.setQuestion(question.getQuestion());
                    List<TenantQuestionnaireAnswer> answers = tenantQuestionnaireAnswerService.listAllQnAnswers(question.getId());
                    for (int j = 0; j < answers.size(); j++) {
                        QnCensus.QnAnswerCensus ansCensus = census.new QnAnswerCensus();
                        ansCensus.setAnswer(answers.get(j).getAnswer());
                        census.getAnsCensus().add(ansCensus);
                    }
                    censuses.add(census);
                }
                Map<String, Object> p_map = new HashMap<String, Object>();
                p_map.put("task_id", qtask_id);
                p_map.put("questionnaire_id", qn_id);
                p_map.put("finished", 1);
                List<TenantQuestionnaireTaskInfo> infos = tenantQuestionnaireTaskInfoService.listAllQnTaskInfos(p_map);
                getListQnCensuses(task, censuses, infos);
                TenantQuestionnaires questionnaire = tenantQuestionnairesService.findQuestionnaireById(qn_id);
                mapT.put("id", questionnaire.getId());
                mapT.put("name", questionnaire.getQuestionnaire_name());
                mapT.put("point_type", questionnaire.getPoint_type());
                mapT.put("list", censuses);
                list.add(mapT);
            }
            map.clear();
            map.put("total", list.size());
            map.put("qnlist", list);
            map.put("task_id", qtask_id);
            mResponseData.setData(map);
        } catch (Exception e) {
            e.printStackTrace();
            mResponseData.setMsg("操作失败!");
            mResponseData.setCode(-1);
        }
        return mResponseData;
    }

    /**
     * 问卷选项统计导出
     *
     * @param qtask_id 任务id
     * @return
     */
    @RequestMapping("/qnAnswerCensusExport")
    public void qnAnswerCensusExport(Long qtask_id, HttpServletResponse response, String admin_uuid) {
        List<List<QnCensus>> list = new ArrayList<>();
        List<String> nameList = new ArrayList<>();
        List<Integer> maxAnswerList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();

        try {
            /* AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(admin_uuid);*/
            TenantQuestionnaireTasks task = tenantQuestionnaireTasksService.selectByPrimaryKey(qtask_id);
            String fileName = task.getName() + "-问卷选项统计";
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
            String[] qn_ids = task.getQuestionnaire_ids().split(","); // 任务中有多个问卷
            for (int index = 0; index < qn_ids.length; index++) {
                Map<String, Object> mapT = new HashMap<>();
                Long qn_id = Long.valueOf(qn_ids[index]);
                List<TenantQuestionnaireQuestion> questions = tenantQuestionnaireQuestionService.listQnQuestionAllList(qn_id);
                List<QnCensus> censuses = new ArrayList<QnCensus>();
                for (int i = 0; i < questions.size(); i++) {
                    QnCensus census = new QnCensus();
                    TenantQuestionnaireQuestion question = questions.get(i);
                    census.setQuestion(question.getQuestion());
                    List<TenantQuestionnaireAnswer> answers = tenantQuestionnaireAnswerService.listAllQnAnswers(question.getId());
                    for (int j = 0; j < answers.size(); j++) {
                        QnCensus.QnAnswerCensus ansCensus = census.new QnAnswerCensus();
                        ansCensus.setAnswer(answers.get(j).getAnswer());
                        census.getAnsCensus().add(ansCensus);
                    }
                    censuses.add(census);
                }
                Map<String, Object> p_map = new HashMap<String, Object>();
                p_map.put("task_id", qtask_id);
                p_map.put("questionnaire_id", qn_id);
                p_map.put("finished", 1);
                List<TenantQuestionnaireTaskInfo> infos = tenantQuestionnaireTaskInfoService.listAllQnTaskInfos(p_map);
                TenantQuestionnaires questionnaire = tenantQuestionnairesService.findQuestionnaireById(qn_id);
                nameList.add(questionnaire.getQuestionnaire_name());
                maxAnswerList.add(questionnaire.getMax_answer());
                getListQnCensuses(task, censuses, infos);
                list.add(censuses);
            }
            OutputStream os = response.getOutputStream();
            getExcelForCC(list, nameList, maxAnswerList, os);
         /*   String operation = adminUserInfoByUuid.getUser_name() + AdminCommon.COMMON_EXPORT + "问卷统计表格";
            setLogs(adminUserInfoByUuid, operation, "user");*/
        } catch (Exception e) {
            e.printStackTrace();

        }
        return;
    }

    private void getListQnCensuses(TenantQuestionnaireTasks task, List<QnCensus> censuses, List<TenantQuestionnaireTaskInfo> infos) {
        for (int i = 0; i < infos.size(); i++) {
            String answer = infos.get(i).getAnswer();
            String[] args = answer.split("\\|");
            for (int j = 0; j < args.length; j++) { // 选择1表示对应题目选择了第一个选项，则第一个选项对应的人数加1
                if (!censuses.get(j).getAnsCensus().isEmpty()) {
                    if (args[j].contains(",")) {
                        String[] margs = args[j].split(",");
                        for (int k = 0; k < margs.length; k++) {
                            QnCensus.QnAnswerCensus ans_census = censuses.get(j).getAnsCensus().get(Integer.valueOf(margs[k]) - 1);
                            ans_census.setUser_nums(ans_census.getUser_nums() + 1);
                            ans_census
                                    .setPercentage(String.valueOf(ans_census.getUser_nums() * 100 / task.getFinish_num()));
                        }

                    } else {
                        QnCensus.QnAnswerCensus ans_census = censuses.get(j).getAnsCensus().get(Integer.valueOf(args[j]) - 1);
                        ans_census.setUser_nums(ans_census.getUser_nums() + 1);
                        ans_census
                                .setPercentage(String.valueOf(ans_census.getUser_nums() * 100 / task.getFinish_num()));
                    }
                }
            }
        }
    }

    private void getExcelForCC(List<List<QnCensus>> list, List<String> nameList, List<Integer> maxAnswerList, OutputStream os)
            throws IOException, WriteException, RowsExceededException {
        WritableWorkbook wwb = null;
        // 创建可写入的Excel工作簿
        wwb = jxl.Workbook.createWorkbook(os);
        List<WritableSheet> wsList = new ArrayList<>();
        for (int i = 0; i < nameList.size(); i++) {
            WritableSheet ws = wwb.createSheet(nameList.get(i), i);
            wsList.add(ws);
        }
        // 查询数据库中所有的数据
        Map<String, Object> umap = new HashMap<String, Object>();
        for (int i = 0; i < nameList.size(); i++) {
            paintingForCC(wsList.get(i), maxAnswerList.get(i));
        }
        for (int i = 0; i < nameList.size(); i++) {
            fillDataForCC(wsList.get(i), list.get(i));
        }
        // 写进文档
        wwb.write();
        // 关闭Excel工作簿对象
        wwb.close();
    }

    private void paintingForCC(WritableSheet ws, Integer maxAnswer) throws WriteException, RowsExceededException {
        Label times2 = new Label(0, 0, "题目");
        List<Label> mLabelList = new ArrayList<>();
        mLabelList.add(times2);
        for (Integer i = 0; i < maxAnswer; i++) {
            mLabelList.add(new Label(i * 3 + 1, 0, "选项" + (i + 1)));
            mLabelList.add(new Label(i * 3 + 2, 0, "选择人数"));
            mLabelList.add(new Label(i * 3 + 3, 0, "百分比"));
        }
        for (int i = 0; i < mLabelList.size(); i++) {
            ws.addCell(mLabelList.get(i));
        }
    }

    private void fillDataForCC(WritableSheet ws, List<QnCensus> reports)
            throws WriteException, RowsExceededException {
        List<Label> mLabelList = new ArrayList<>();
        for (int i = 0; i < reports.size(); i++) {
            String question = reports.get(i).getQuestion();
            List<QnCensus.QnAnswerCensus> ansCensus = reports.get(i).getAnsCensus();
            mLabelList.add(new Label(0, i + 1, question));
            for (int i1 = 0; i1 < ansCensus.size(); i1++) {
                mLabelList.add(new Label((i1) * 3 + 1, i + 1, ansCensus.get(i1).getAnswer()));
                mLabelList.add(new Label((i1) * 3 + 2, i + 1, ansCensus.get(i1).getUser_nums() + ""));
                mLabelList.add(new Label((i1) * 3 + 3, i + 1, ansCensus.get(i1).getPercentage()));
            }
        }
        for (int i = 0; i < mLabelList.size(); i++) {
            ws.addCell(mLabelList.get(i));
        }
    }

    /**
     * 问卷统计-分数段
     *
     * @param framework_id
     * @param level            层级
     * @param score_ranges     分数段：以逗号分割
     * @param questionnaire_id 问卷id
     * @param task_ids         任务id
     * @param begin_date
     * @param end_date
     * @return
     */
    @RequestMapping("/frameworkScoreStatistics")
    @ResponseBody
    public ResponseData frameworkScoreStatistics(@RequestParam Long framework_id, @RequestParam Integer level, @RequestParam String score_ranges,
                                                 @RequestParam Long questionnaire_id, @RequestParam String task_ids, String begin_date, String end_date) {
        ResponseData responseData = new ResponseData();
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> retMap = new HashMap<String, Object>();
        if (level > 2) {
            responseData.setCode(-1);
            responseData.setMsg("level参数错误！");
            return responseData;
        }

        Map<String, Object> tree = getTenantFrameworksTreeMap(framework_id, level);
//        getframeworkDatas(framework_id, null, map);
        getTreePathDatas(framework_id, map);
        List<Integer> scoreList = Arrays.asList(score_ranges.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
        Collections.sort(scoreList, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        });
        List<String> treePaths = getTenantFrameworksId(framework_id, level);
        if (StringUtils.isNotEmpty(begin_date)) {
            map.put("begin_date", begin_date);
        }
        if (StringUtils.isNotEmpty(end_date)) {
            map.put("end_date", end_date);
        }
        List<Long> taskIdList = new ArrayList<Long>();
        if (StringUtils.isNotEmpty(task_ids)) {
            taskIdList = Arrays.asList(task_ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        }
        map.put("questionnaire_id", questionnaire_id);
        map.put("task_ids", taskIdList);
        map.put("score_ranges", scoreList);
        map.put("tree_paths", treePaths);
        List<String> scoreStringList = scoreList.stream().map(s -> String.valueOf(s)).collect(Collectors.toList());
        scoreStringList.add("other");
        List<Map<String, Object>> statisticsList = tenantQuestionnaireTaskInfoService.frameworkScoreStatistics(map);
        Map<String, Object> scoreMap = new HashMap<>();
        for (Map<String, Object> temp : statisticsList) {
            for (String treePath : treePaths) {
                if (temp.get(treePath) != null) {
                    scoreMap.put(treePath + temp.get("score_range").toString(), temp.get(treePath));
                }
            }
        }
        List<Map<String, Object>> sub = (List<Map<String, Object>>) tree.get("sub");
        ;
        Map<String, Object> totalMap = new HashMap<>();
        List<Map<String, Object>> totalMapList = new ArrayList<>();
        List<Integer> totalCountList = new ArrayList<>();
        if (statisticsList.size() > 0) {
            if (level == 1) {
                for (Map<String, Object> subMap : sub) {
                    List<Integer> oneCountList = new ArrayList<>();
                    for (String score : scoreStringList) {
                        int count = scoreMap.get(subMap.get("framework_id") + score) == null ? 0 : Integer.parseInt(scoreMap.get(subMap.get("framework_id") + score).toString());
                        oneCountList.add(count);
                    }
                    Map<String, Object> oneMap = new HashMap<>();
                    oneMap.put("list", oneCountList);
                    oneMap.put("row", subMap.get("framework_name"));
                    totalMapList.add(oneMap);
                }

                for (String score : scoreStringList) {
                    int count = scoreMap.get(tree.get("framework_id") + score) == null ? 0 : Integer.parseInt(scoreMap.get(tree.get("framework_id") + score).toString());
                    totalCountList.add(count);
                }
                totalMap.put("list", totalCountList);
                totalMap.put("row", tree.get("framework_name"));
                totalMapList.add(0, totalMap);
            } else {
                for (Map<String, Object> subMap : sub) {
                    List<Map<String, Object>> oneMapList = new ArrayList<>();
                    List<Map<String, Object>> tempList = (List<Map<String, Object>>) subMap.get("sub");
                    for (Map<String, Object> tempMap : tempList) {
                        List<Integer> twoCountList = new ArrayList<>();
                        for (String score : scoreStringList) {
                            int count = scoreMap.get(tempMap.get("framework_id").toString() + score) == null ? 0 : Integer.parseInt(scoreMap.get(tempMap.get("framework_id").toString() + score).toString());
                            twoCountList.add(count);
                        }
                        Map<String, Object> twoMap = new HashMap<>();
                        twoMap.put("list", twoCountList);
                        twoMap.put("row", tempMap.get("framework_name"));
                        oneMapList.add(twoMap);
                    }

                    List<Integer> oneCountList = new ArrayList<>();
                    for (String score : scoreStringList) {
                        int count = scoreMap.get(subMap.get("framework_id") + score) == null ? 0 : Integer.parseInt(scoreMap.get(subMap.get("framework_id") + score).toString());
                        oneCountList.add(count);
                    }

                    Map<String, Object> oneMap = new HashMap<>();
                    oneMap.put("list", oneCountList);
                    oneMap.put("row", subMap.get("framework_name"));
                    oneMapList.add(0, oneMap);
                    totalMapList.addAll(oneMapList);
                }

                for (String score : scoreStringList) {
                    int count = scoreMap.get(tree.get("framework_id") + score) == null ? 0 : Integer.parseInt(scoreMap.get(tree.get("framework_id") + score).toString());
                    totalCountList.add(count);
                }

                totalMap.put("list", totalCountList);
                totalMap.put("row", tree.get("framework_name"));
                totalMapList.add(0, totalMap);
            }
        }
        List<String> headChStringList = new ArrayList<>();
        headChStringList.add("组织机构");
        for (int i = 0; i < scoreStringList.size(); i++) {
            headChStringList.add(getScoreString(scoreStringList, i));
        }
        retMap.put("headList", headChStringList);
        retMap.put("list", totalMapList);
        responseData.setData(retMap);
        return responseData;
    }

    /**
     * 导出问卷分数段统计
     *
     * @param response
     * @param framework_id
     * @param level
     * @param score_ranges
     * @param questionnaire_id
     * @param task_ids
     * @param begin_date
     * @param end_date
     * @param file_type
     * @throws IOException
     */
    @RequestMapping("/exportFrameworkScoreStatistics")
    public void exportFrameworkScoreStatistics(HttpServletResponse response, @RequestParam Long framework_id, @RequestParam Integer level,
                                               @RequestParam String score_ranges, @RequestParam Long questionnaire_id, @RequestParam String task_ids,
                                               String begin_date, String end_date, String file_type) throws IOException {
        String fileName = "问卷分数段统计";
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        if (file_type == null || "1".equals(file_type)) {
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        } else {
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));
        }

        OutputStream os = response.getOutputStream();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            WritableWorkbook wwb = null;
            // 创建可写入的Excel工作簿
            wwb = jxl.Workbook.createWorkbook(os);
            WritableSheet ws = wwb.createSheet("问卷分数段统计", 0);
            ResponseData responseData = new ResponseData();
            responseData = frameworkScoreStatistics(framework_id, level, score_ranges, questionnaire_id, task_ids, begin_date, end_date);
            List<Map<String, Object>> totalMapList = new ArrayList<>();
            totalMapList = (List<Map<String, Object>>) responseData.getData().get("list");
            List<String> titles = (List<String>) responseData.getData().get("headList");
            // 要插入到的Excel表格的行号，默认从0开始
            for (int i = 0; i < titles.size(); i++) {
                ws.addCell(new Label(i, 0, titles.get(i)));
            }

            for (int j = 0; j < totalMapList.size(); j++) {
                Map<String, Object> sub = totalMapList.get(j);
                int row = j + 1;
                ws.addCell(new Label(0, row, sub.get("row").toString().replace("果果心理", "/").replace("//", "/")));
                List<Integer> countList = (List<Integer>) sub.get("list");
                for (int k = 0; k < countList.size(); k++) {
                    int col = k + 1;
                    ws.addCell(new Label(col, row, countList.get(k).toString()));
                }
            }
            // 写进文档
            wwb.write();
            // 关闭Excel工作簿对象
            wwb.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                os.close();
            }
        }
    }

    /**
     * 问卷统计-分数段 用户
     *
     * @param framework_id
     * @param level            层级
     * @param score_ranges     分数段：以逗号分割
     * @param questionnaire_id 问卷id
     * @param task_ids         任务id
     * @param begin_date
     * @param end_date
     * @return
     */
    @RequestMapping("/frameworkScoreStatisticsUser")
    @ResponseBody
    public ResponseData frameworkScoreStatisticsUser(@RequestParam Long framework_id, @RequestParam Integer level, @RequestParam String score_ranges,
                                                     @RequestParam Long questionnaire_id, @RequestParam String task_ids,
                                                     @RequestParam String dimension, @RequestParam String location,
                                                     Integer currentPage, Integer pageSize,
                                                     String begin_date, String end_date) {
        PageInfo pi = new PageInfo();
        if (currentPage != null && pageSize != null) {
            pi.setCurrentPage(currentPage);
            pi.setPageSize(pageSize);
        }
        ResponseData responseData = new ResponseData();
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> retMap = new HashMap<String, Object>();
        if (level > 2) {
            responseData.setCode(-1);
            responseData.setMsg("level参数错误！");
            return responseData;
        }
        Map<String, Object> tree = getTenantFrameworksTreeMap(framework_id, level);
//        getframeworkDatas(framework_id, null, map);
        getTreePathDatas(framework_id, map);
        List<Integer> scoreList = Arrays.asList(score_ranges.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
        Collections.sort(scoreList, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        });
        List<String> treePaths = getTenantFrameworksId(framework_id, level);
        if (StringUtils.isNotEmpty(begin_date)) {
            map.put("begin_date", begin_date);
        }
        if (StringUtils.isNotEmpty(end_date)) {
            map.put("end_date", end_date);
        }
        List<Long> taskIdList = new ArrayList<Long>();
        if (StringUtils.isNotEmpty(task_ids)) {
            taskIdList = Arrays.asList(task_ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        }
        map.put("questionnaire_id", questionnaire_id);
        map.put("task_ids", taskIdList);
        map.put("score_ranges", scoreList);
        map.put("tree_paths", treePaths);
        List<String> scoreStringList = scoreList.stream().map(s -> String.valueOf(s)).collect(Collectors.toList());
        scoreStringList.add("other");
        if (location != null && location != "") {
            if (location.contains("包含")) {
                String[] split = location.split("\\(");
                split = split[0].split("-");
                Integer begin = Integer.parseInt(split[0]);
                Integer end = Integer.parseInt(split[1]);
                map.put("begin_index", begin);
                map.put("end_index", end);
            } else {
                location = location.replace("以上", "").trim();
                map.put("begin_index", Integer.parseInt(location));
            }
        }
        Map<String, Object> fMap = new HashMap<>();
        fMap.put("whole_frame_name", dimension);
//        TenantFrameworks framework = tenantFrameworksService.getFrameworkByName(fMap);
//        map.put("whole_name_id", framework.getTree_path());
        List<Map<String, Object>> statisticsList = tenantQuestionnaireTaskInfoService.frameworkScoreStatisticsUser(pi, map);

        retMap.put("list", statisticsList);
        responseData.setData(retMap);
        return responseData;
    }


    /**
     * 问卷统计-分数段 导出用户
     *
     * @param framework_id
     * @param level            层级
     * @param score_ranges     分数段：以逗号分割
     * @param questionnaire_id 问卷id
     * @param task_ids         任务id
     * @param begin_date
     * @param end_date
     * @return
     */
    @RequestMapping("/excelFrameworkScoreStatisticsUser")
    @ResponseBody
    public ResponseData excelFrameworkScoreStatisticsUser(@RequestParam Long framework_id, @RequestParam Integer level, @RequestParam String score_ranges,
                                                          @RequestParam Long questionnaire_id, @RequestParam String task_ids,
                                                          @RequestParam String dimension, @RequestParam String location,
                                                          String begin_date, String end_date, String file_type, HttpServletResponse response) throws Exception {
        ResponseData responseData = new ResponseData();
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> retMap = new HashMap<String, Object>();
        if (level > 2) {
            responseData.setCode(-1);
            responseData.setMsg("level参数错误！");
            return responseData;
        }
        Map<String, Object> tree = getTenantFrameworksTreeMap(framework_id, level);
//        getframeworkDatas(framework_id, null, map);
        getTreePathDatas(framework_id, map);
        List<Integer> scoreList = Arrays.asList(score_ranges.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
        Collections.sort(scoreList, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        });
        List<String> treePaths = getTenantFrameworksId(framework_id, level);
        if (StringUtils.isNotEmpty(begin_date)) {
            map.put("begin_date", begin_date);
        }
        if (StringUtils.isNotEmpty(end_date)) {
            map.put("end_date", end_date);
        }
        List<Long> taskIdList = new ArrayList<Long>();
        if (StringUtils.isNotEmpty(task_ids)) {
            taskIdList = Arrays.asList(task_ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        }
        map.put("questionnaire_id", questionnaire_id);
        map.put("task_ids", taskIdList);
        map.put("score_ranges", scoreList);
        map.put("tree_paths", treePaths);
        List<String> scoreStringList = scoreList.stream().map(s -> String.valueOf(s)).collect(Collectors.toList());
        scoreStringList.add("other");
        if (location != null && location != "") {
            if (location.contains("包含")) {
                String[] split = location.split("\\(");
                split = split[0].split("-");
                Integer begin = Integer.parseInt(split[0]);
                Integer end = Integer.parseInt(split[1]);
                map.put("begin_index", begin);
                map.put("end_index", end);
            } else {
                location = location.replace("以上", "").trim();
                map.put("begin_index", Integer.parseInt(location));
            }
        }
        Map<String, Object> fMap = new HashMap<>();
        fMap.put("whole_frame_name", dimension);
//        TenantFrameworks framework = tenantFrameworksService.getFrameworkByName(fMap);
//        map.put("whole_name_id", framework.getTree_path());
        List<Map<String, Object>> statisticsList = tenantQuestionnaireTaskInfoService.frameworkScoreStatisticsUser(null, map);

        String fileName = "人员导出统计";
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        if (file_type == null || "1".equals(file_type)) {
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        } else {
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));
        }
        OutputStream os = response.getOutputStream();
        try {
            WritableWorkbook wwb = null;
            // 创建可写入的Excel工作簿
            wwb = jxl.Workbook.createWorkbook(os);
            WritableSheet ws = wwb.createSheet("公安应激", 0);
            //c 列   r 行
            //要插入到的Excel表格的行号，默认从0开始
            Label user_name = new Label(0, 0, "用户名");
            Label real_name = new Label(1, 0, "真实姓名");
            Label user_sex = new Label(2, 0, "性别");
            Label user_framework = new Label(3, 0, "组织机构");
            Label user_submit = new Label(4, 0, "答题提交时间");
            ws.addCell(user_name);
            ws.addCell(real_name);
            ws.addCell(user_sex);
            ws.addCell(user_framework);
            ws.addCell(user_submit);

            for (int k = 0; k < statisticsList.size(); k++) {
                Label name_k_1 = new Label(0, k + 1, statisticsList.get(k).get("user_name").toString());
                Label name_k_2 = new Label(1, k + 1, statisticsList.get(k).get("real_name").toString());
                Label name_k_3 = new Label(2, k + 1, statisticsList.get(k).get("user_gender").toString().equals("1") ? "男" : "女");
                Label name_k_4 = new Label(3, k + 1, statisticsList.get(k).get("whole_name").toString());
                Label name_k_5 = new Label(4, k + 1, statisticsList.get(k).get("submit_date").toString());
                ws.addCell(name_k_1);
                ws.addCell(name_k_2);
                ws.addCell(name_k_3);
                ws.addCell(name_k_4);
                ws.addCell(name_k_5);
            }
            //写进文档
            wwb.write();
            System.out.println("Excel导出成功！");
            // 关闭Excel工作簿对象
            wwb.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                os.close();
            }
        }
        return null;
    }


    /**
     * 问卷统计-题目选项
     *
     * @param framework_id
     * @param questionnaire_id
     * @param task_ids
     * @param begin_date
     * @param end_date
     * @return
     */
    @RequestMapping("/subjectOptionStatistics")
    @ResponseBody
    public ResponseData subjectOptionStatistics(@RequestParam Long framework_id, @RequestParam Long questionnaire_id,
                                                @RequestParam String task_ids, String begin_date, String end_date) {
        ResponseData responseData = new ResponseData();
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> retMap = new HashMap<String, Object>();

        getframeworkDatas(framework_id, null, map);
        if (StringUtils.isNotEmpty(begin_date)) {
            map.put("begin_date", begin_date);
        }
        if (StringUtils.isNotEmpty(end_date)) {
            map.put("end_date", end_date);
        }
        List<Long> taskIdList = new ArrayList<Long>();
        if (StringUtils.isNotEmpty(task_ids)) {
            taskIdList = Arrays.asList(task_ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        }
        map.put("questionnaire_id", questionnaire_id);
        map.put("task_ids", taskIdList);
        Map<String, Object> subjectMap = new HashMap<String, Object>();
        List<Map<String, Object>> statisticsList = tenantQuestionnaireTaskInfoService.subjectOptionStatistics(map);
        for (Map<String, Object> subMap : statisticsList) {
            List<Integer> answerList = Arrays.asList(subMap.get("answer").toString().split("\\|")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
            for (int i = 0; i < answerList.size(); i++) {
                String unionName = subMap.get("questionnaire_id").toString() + "-" + (i + 1) + "-" + answerList.get(i);
                if (subjectMap.get(unionName) == null) {
                    subjectMap.put(unionName, 1);
                } else {
                    subjectMap.put(unionName, Integer.parseInt(subjectMap.get(unionName).toString()) + 1);
                }
            }
        }

        int maxOptionLength = 0;
        List<Map<String, Object>> allList = new ArrayList<>();
        if (statisticsList.size() > 0) {
            List<TenantQuestionnaireQuestion> qnQuestionList = tenantQuestionnaireQuestionService.listQnQuestionAllList(questionnaire_id);
            for (int j = 0; j < qnQuestionList.size(); j++) {
                Map<String, Object> optionMap = new HashMap<>();
                List<TenantQuestionnaireAnswer> qnAnswerList = tenantQuestionnaireAnswerService.listAllQnAnswers(qnQuestionList.get(j).getId());
                if (maxOptionLength < qnAnswerList.size()) {
                    maxOptionLength = qnAnswerList.size();
                }
                List<Integer> countList = new ArrayList<>();
                for (int k = 0; k < qnAnswerList.size(); k++) {
                    String unionName = questionnaire_id + "-" + (j + 1) + "-" + qnAnswerList.get(k).getSort_code();
                    int count = subjectMap.get(unionName) == null ? 0 : Integer.parseInt(subjectMap.get(unionName).toString());
                    countList.add(count);
                }
                optionMap.put("row", "第" + (j + 1) + "题");
                optionMap.put("list", countList);
                allList.add(optionMap);
            }
        }

        List<String> headChStringList = new ArrayList<>();
        headChStringList.add("问卷题目");
        for (int k = 1; k < maxOptionLength + 1; k++) {
            headChStringList.add("选项" + k);
        }
        retMap.put("headList", headChStringList);
        retMap.put("list", allList);
        responseData.setData(retMap);
        return responseData;
    }

    /**
     * 问卷统计-题目选项用户
     *
     * @param framework_id
     * @param questionnaire_id
     * @param task_ids
     * @param begin_date
     * @param end_date
     * @return
     * @Param coordinate 坐标
     */
    @RequestMapping("/subjectOptionStatisticsUser")
    @ResponseBody
    public ResponseData subjectOptionStatisticsUser(@RequestParam Long framework_id, @RequestParam Long questionnaire_id,
                                                    @RequestParam String task_ids, @RequestParam String dimension,
                                                    @RequestParam String location, Integer currentPage, Integer pageSize, String begin_date, String end_date) {
        ResponseData responseData = new ResponseData();
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> retMap = new HashMap<String, Object>();

        PageInfo pi = new PageInfo();
        if (currentPage != null && pageSize != null) {
            pi.setCurrentPage(currentPage);
            pi.setPageSize(pageSize);
        }
        getframeworkDatas(framework_id, null, map);
        if (StringUtils.isNotEmpty(begin_date)) {
            map.put("begin_date", begin_date);
        }
        if (StringUtils.isNotEmpty(end_date)) {
            map.put("end_date", end_date);
        }
        List<Long> taskIdList = new ArrayList<Long>();
        if (StringUtils.isNotEmpty(task_ids)) {
            taskIdList = Arrays.asList(task_ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        }
        map.put("questionnaire_id", questionnaire_id);
        map.put("task_ids", taskIdList);
        dimension = dimension.replace("第", "").replace("题", "").trim();
        location = location.replace("选项", "").trim();
        map.put("size", Integer.parseInt(dimension) * 2 - 1);
        map.put("answer", Integer.parseInt(location));

        List<Map<String, Object>> statisticsList = tenantQuestionnaireTaskInfoService.subjectOptionStatisticsUser(pi, map);
        retMap.put("list", statisticsList);
        responseData.setData(retMap);
        return responseData;
    }

    /**
     * 问卷统计-导出题目选项用户
     *
     * @param framework_id
     * @param questionnaire_id
     * @param task_ids
     * @param begin_date
     * @param end_date
     * @return
     * @Param coordinate 坐标
     */
    @RequestMapping("/excelSubjectOptionStatisticsUser")
    @ResponseBody
    public ResponseData excelSubjectOptionStatisticsUser(@RequestParam Long framework_id, @RequestParam Long questionnaire_id,
                                                         @RequestParam String task_ids, @RequestParam String dimension,
                                                         @RequestParam String location, String begin_date, String end_date,
                                                         String file_type, HttpServletResponse response) throws Exception {
        ResponseData responseData = new ResponseData();
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> retMap = new HashMap<String, Object>();
        getframeworkDatas(framework_id, null, map);
        if (StringUtils.isNotEmpty(begin_date)) {
            map.put("begin_date", begin_date);
        }
        if (StringUtils.isNotEmpty(end_date)) {
            map.put("end_date", end_date);
        }
        List<Long> taskIdList = new ArrayList<Long>();
        if (StringUtils.isNotEmpty(task_ids)) {
            taskIdList = Arrays.asList(task_ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        }
        map.put("questionnaire_id", questionnaire_id);
        map.put("task_ids", taskIdList);
        dimension = dimension.replace("第", "").replace("题", "").trim();
        location = location.replace("选项", "").trim();
        map.put("size", Integer.parseInt(dimension) * 2 - 1);
        map.put("answer", Integer.parseInt(location));

        List<Map<String, Object>> statisticsList = tenantQuestionnaireTaskInfoService.subjectOptionStatisticsUser(null, map);
        String fileName = "人员导出统计";
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        if (file_type == null || "1".equals(file_type)) {
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        } else {
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));
        }
        OutputStream os = response.getOutputStream();
        try {
            WritableWorkbook wwb = null;
            // 创建可写入的Excel工作簿
            wwb = jxl.Workbook.createWorkbook(os);
            WritableSheet ws = wwb.createSheet("公安应激", 0);
            //c 列   r 行
            //要插入到的Excel表格的行号，默认从0开始
            Label user_name = new Label(0, 0, "用户名");
            Label real_name = new Label(1, 0, "真实姓名");
            Label user_sex = new Label(2, 0, "性别");
            Label user_framework = new Label(3, 0, "组织机构");
            Label user_submit = new Label(4, 0, "答题提交时间");
            ws.addCell(user_name);
            ws.addCell(real_name);
            ws.addCell(user_sex);
            ws.addCell(user_framework);
            ws.addCell(user_submit);

            for (int k = 0; k < statisticsList.size(); k++) {
                Label name_k_1 = new Label(0, k + 1, statisticsList.get(k).get("user_name").toString());
                Label name_k_2 = new Label(1, k + 1, statisticsList.get(k).get("real_name").toString());
                Label name_k_3 = new Label(2, k + 1, statisticsList.get(k).get("user_gender").toString().equals("1") ? "男" : "女");
                Label name_k_4 = new Label(3, k + 1, statisticsList.get(k).get("whole_name").toString());
                Label name_k_5 = new Label(4, k + 1, statisticsList.get(k).get("submit_date").toString());
                ws.addCell(name_k_1);
                ws.addCell(name_k_2);
                ws.addCell(name_k_3);
                ws.addCell(name_k_4);
                ws.addCell(name_k_5);
            }
            //写进文档
            wwb.write();
            System.out.println("Excel导出成功！");
            // 关闭Excel工作簿对象
            wwb.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                os.close();
            }
        }
        return null;
    }

    /**
     * 导出问卷题目统计
     *
     * @param response
     * @param framework_id
     * @param questionnaire_id
     * @param task_ids
     * @param begin_date
     * @param end_date
     * @param file_type
     * @throws IOException
     */
    @RequestMapping("/exportSubjectOptionStatistics")
    public void exportSubjectOptionStatistics(HttpServletResponse response, @RequestParam Long framework_id,
                                              @RequestParam Long questionnaire_id, @RequestParam String task_ids,
                                              String begin_date, String end_date, String file_type) throws IOException {
        String fileName = "问卷题目统计";
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        if (file_type == null || "1".equals(file_type)) {
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        } else {
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));
        }

        OutputStream os = response.getOutputStream();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            WritableWorkbook wwb = null;
            // 创建可写入的Excel工作簿
            wwb = jxl.Workbook.createWorkbook(os);
            WritableSheet ws = wwb.createSheet("问卷题目统计", 0);
            ResponseData responseData = new ResponseData();
            responseData = subjectOptionStatistics(framework_id, questionnaire_id, task_ids, begin_date, end_date);
            List<Map<String, Object>> totalMapList = new ArrayList<>();
            totalMapList = (List<Map<String, Object>>) responseData.getData().get("list");
            List<String> titles = (List<String>) responseData.getData().get("headList");
            // 要插入到的Excel表格的行号，默认从0开始
            for (int i = 0; i < titles.size(); i++) {
                ws.addCell(new Label(i, 0, titles.get(i)));
            }
            for (int j = 0; j < totalMapList.size(); j++) {
                Map<String, Object> sub = totalMapList.get(j);
                int row = j + 1;
                ws.addCell(new Label(0, row, sub.get("row").toString()));
                List<Integer> countList = (List<Integer>) sub.get("list");
                for (int k = 0; k < countList.size(); k++) {
                    int col = k + 1;
                    ws.addCell(new Label(col, row, countList.get(k).toString()));
                }
            }
            // 写进文档
            wwb.write();
            // 关闭Excel工作簿对象
            wwb.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                os.close();
            }
        }
    }

    private Map<String, Object> getTenantFrameworksTreeMap(Long parentId, Integer level) {
        Map<String, Object> retmap = new HashMap<>();
        List<Map<String, Object>> mapList = new ArrayList<>();
        TenantFrameworks tenantFrameworks = tenantFrameworksService.getFrameworkById(parentId);
        if (level > 0) {
            mapList = getSubTenantFrameworksTreeMap(parentId, level);
            level = level - 1;
            if (level > 0) {
                for (Map<String, Object> map : mapList) {
                    List<Map<String, Object>> subList = new ArrayList<>();
                    subList = getSubTenantFrameworksTreeMap(Long.parseLong(map.get("framework_id").toString()), level);
                    map.put("sub", subList);
                }
            }
        }
        retmap.put("framework_name", tenantFrameworks.getWhole_name());
        retmap.put("framework_id", parentId);
        retmap.put("sub", mapList);
        return retmap;
    }

    private List<Map<String, Object>> getSubTenantFrameworksTreeMap(Long parentId, Integer level) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        List<TenantFrameworks> tempList = tenantFrameworksService.listAllSonFrameworkByFatherId(parentId);
        if (!tempList.isEmpty()) {
            for (TenantFrameworks mTenantFrameworks : tempList) {
                if (!mapList.contains(mTenantFrameworks.getId())) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("framework_name", mTenantFrameworks.getWhole_name());
                    map.put("framework_id", mTenantFrameworks.getId());
                    mapList.add(map);
                    if (level == 1) {
                        List<Long> allTenantFrameworksId = getAllSonTenantFrameworksId(mTenantFrameworks.getId());
                        map.put("ids", allTenantFrameworksId);
                    }
                }
            }
        }
        return mapList;
    }

    private String getScoreString(List<String> scoreStringList, int i) {
        String str = scoreStringList.get(i);
        if (i == 0) {
            str = "0-" + str + "(包含" + str + ")";
        } else if (scoreStringList.get(i).equals("other")) {
            str = scoreStringList.get(i - 1) + "以上";
        } else {
            str = scoreStringList.get(i - 1) + "-" + str + "(包含" + str + ")";
        }
        return str;
    }

    private List<String> getTenantFrameworksId(Long parentId, Integer level) {
        List<String> idList = new ArrayList<>();
        List<String> ids = new ArrayList<>();
        if (level > 0) {
            idList = getSubTenantFrameworksId(parentId.toString());
            ids.add(parentId.toString());
            ids.addAll(idList);
            level = level - 1;
            if (level > 0) {
                for (String id : idList) {
                    List<String> subId = new ArrayList<>();
                    subId = getSubTenantFrameworksId(id);
                    ids.addAll(subId);
                }
            }
        } else if (level == 0) {
            ids.add(parentId.toString());
        }
        return ids;
    }

    private List<String> getSubTenantFrameworksId(String parentId) {
        List<String> idList = new ArrayList<>();
        List<TenantFrameworks> tempList = tenantFrameworksService.listAllSonFrameworkByFatherId(Long.valueOf(parentId));
        for (TenantFrameworks mTenantFrameworks : tempList) {
            if (!idList.contains(mTenantFrameworks.getId())) {
                idList.add(mTenantFrameworks.getId().toString());
            }
        }
        return idList;
    }

    /**
     * 获取问卷列表
     *
     * @param framework_id
     * @return
     */
    @RequestMapping(value = "/getAllQnList")
    @ResponseBody
    public ResponseData getAllQnList(@RequestParam Long framework_id) {
        ResponseData responseData = new ResponseData();
        Map<String, Object> retMap = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        getframeworkDatas(framework_id, null, map);
        List<Map<String, Object>> list = tenantQuestionnairesService.getAllQnList(map);
        for (Map<String, Object> stringObjectMap : list) {
            Object id = stringObjectMap.get("id");
            stringObjectMap.put("questionnaire_id",id);
        }
        retMap.put("list", list);
        responseData.setData(retMap);
        return responseData;
    }

    /**
     * 获取任务列表
     *
     * @param framework_id
     * @param questionnaire_id
     * @return
     */
    @RequestMapping(value = "/getAllQnTasks")
    @ResponseBody
    public ResponseData getAllQnTasks(@RequestParam Long framework_id, @RequestParam Long questionnaire_id) {
        ResponseData responseData = new ResponseData();
        Map<String, Object> retMap = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        getframeworkDatas(framework_id, null, map);
        map.put("questionnaire_id", questionnaire_id);
        List<Map<String, Object>> list = tenantQuestionnaireTasksService.getAllQnTasks(map);
        retMap.put("list", list);
        responseData.setData(retMap);
        return responseData;
    }

    /**
     * @param
     * @param
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/exQnTemplate")
    public String exQnTemplate(HttpServletResponse response, Integer file_type)
            throws IOException {
        String fileName = "问卷模板";
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        if (file_type == null || file_type == 1) {
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        } else {
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));
        }

        // 根据传进来的file对象创建可写入的Excel工作薄
        OutputStream os = response.getOutputStream();
        Map<String, Object> map = new HashMap<String, Object>();
        List<String> mlist = new ArrayList<>();
        mlist.add("题目");
        for (int i = 1; i < 11; i++) {
            mlist.add("选项" + i);
            mlist.add("分数" + i);
        }
        try {
            WritableWorkbook wwb = null;
            // 创建可写入的Excel工作簿
            wwb = jxl.Workbook.createWorkbook(os);
            WritableSheet ws = wwb.createSheet("问卷模板", 0);
            // 查询数据库中所有的数据
            List<Label> mlistLabel = new ArrayList<>();
            for (int i = 0; i < mlist.size(); i++) {
                mlistLabel.add(new Label(i, 0, mlist.get(i)));
            }
            // 要插入到的Excel表格的行号，默认从0开始
            for (int i = 0; i < mlistLabel.size(); i++) {
                ws.addCell(mlistLabel.get(i));
            }
            // 写进文档
            wwb.write();
            // 关闭Excel工作簿对象
            wwb.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                os.close();
            }
        }
        return null;
    }

    /**
     * 导出问卷结果
     *
     * @param
     * @param
     * @return
     */

    @RequestMapping("/listFinishUserAndTaskInfoExcel")
    @ResponseBody
    public  void listFinishUserAndTaskInfoExcel(Long framework_id,
                                                       Integer waring_result, String admin_uuid,
                                                       String user_name, String real_name, String user_gender,
                                                       String test_begin_date, String test_end_date,
                                                       Integer minScore, Integer maxScore,
                                                       Long questionnaire_id, Long task_id,
                                                       String user_uuid, HttpServletResponse response, String file_type) throws IOException {

        Map<String, Object> map = new HashMap<String, Object>();

        AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(admin_uuid);
        TenantFrameworks tenantFrameworks = null;
        String fileName = "";
        if (framework_id != null) {
            tenantFrameworks = tenantFrameworksService.getFrameworkById(framework_id);
        } else {
            tenantFrameworks = tenantFrameworksService.getFrameworkById(adminUserInfoByUuid.getFramework_id());

        }
        String channelId = "";
        if (tenantFrameworks != null) {
            fileName = tenantFrameworks.getName();
            channelId = tenantFrameworks.getChannel_id();
        }
        fileName += "问卷结果答题数据";
        getframeworkDatas(framework_id, adminUserInfoByUuid, map);
        if (waring_result != null)
            map.put("waring_result", waring_result);
        if (questionnaire_id != null)
            map.put("questionnaire_id", questionnaire_id);
        if (task_id != null)
            map.put("task_id", task_id);
        if (minScore != null)
            map.put("minScore", minScore);
        if (maxScore != null)
            map.put("maxScore", maxScore);
        if (!StringUtils.isEmpty(user_name))
            map.put("user_name", user_name);
            map.put("searchName", user_name);
        if (!StringUtils.isEmpty(real_name))
            map.put("real_name", real_name);
        if (!StringUtils.isEmpty(user_gender))
            map.put("user_gender", user_gender);
        if (!StringUtils.isEmpty(test_begin_date))
            map.put("test_begin_date", test_begin_date);
        if (!StringUtils.isEmpty(test_end_date))
            map.put("test_end_date", test_end_date);
        if (!StringUtils.isEmpty(user_uuid))
            map.put("user_uuid", user_uuid);
        Set<Long> set = new HashSet();
        Set<Long> setQuestionnaireId = new HashSet<>();
        List<Map<String, Object>> statisticsList = tenantQuestionnaireTaskInfoService.listFinishUserAndTaskInfo(null, map);
        for (Map<String, Object> stringObjectMap : statisticsList) {
            set.add((Long) stringObjectMap.get("task_id"));
            setQuestionnaireId.add((Long) stringObjectMap.get("questionnaire_id"));
        }
        Map<Long, String> map1 = new HashMap<>();
        Map<Long, String> map2 = new HashMap<>();
        for (Long str : set) {
            TenantQuestionnaireTasks tenantQuestionnaireTasks = tenantQuestionnaireTasksService.selectByPrimaryKey(str);
            map1.put(tenantQuestionnaireTasks.getId(), tenantQuestionnaireTasks.getName());
        }
        for (Long str1 : setQuestionnaireId) {
            TenantQuestionnaires tenantQuestionnaires = tenantQuestionnairesService.selectByPrimaryKey(str1);
            map2.put(tenantQuestionnaires.getId(), tenantQuestionnaires.getQuestionnaire_description());
        }

        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        if (file_type == null || "1".equals(file_type)) {
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        } else {
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));
        }
        OutputStream os = response.getOutputStream();
        WritableWorkbook wwb = null;
        try {
            // 创建可写入的Excel工作簿
            wwb = jxl.Workbook.createWorkbook(os);
            WritableSheet ws = wwb.createSheet("问卷结果答题数据", 0);
            WritableSheet ws1 = wwb.createSheet("问卷答题详情", 1);
            //c 列   r 行
            //要插入到的Excel表格的行号，默认从0开始
            Label waringResult = new Label(0, 0, "风险提示");
            Label questionnaire_name = new Label(1, 0, "问卷名称");
            Label userName = new Label(2, 0, "用户名");
            Label realName = new Label(3, 0, "真实姓名");
            Label nick_name = new Label(4, 0, "微信昵称");
            Label user_phone = new Label(5, 0, "手机号");
            Label userGender = new Label(6, 0, "性别");
            Label user_birth = new Label(7, 0, "出生年月");
            Label whole_name = new Label(8, 0, "组织机构");
            Label user_submit = new Label(9, 0, "完成时间");
            Label task_name = new Label(10, 0, "任务名称");
            Label questionnaire_description = new Label(11, 0, "问卷说明");
            Label answer = new Label(12, 0, "答案集合");

            ws.addCell(waringResult);
            ws.addCell(questionnaire_name);
            ws.addCell(userName);
            ws.addCell(realName);
            ws.addCell(nick_name);
            ws.addCell(user_phone);
            ws.addCell(userGender);
            ws.addCell(user_birth);
            ws.addCell(whole_name);
            ws.addCell(user_submit);
            ws.addCell(task_name);
            ws.addCell(questionnaire_description);
            ws.addCell(answer);

            Map<String,List<String>> map3=new HashMap<>();
            // 查询用户扩展信息
            List<ExtFieldRecord> list = extFieldRecordFeignService.listExtFieldDataByChannelId(channelId);
            if (list.size() > 0) {
                Integer fieldNamecount = 0;
                for (int j = 0; j < list.size(); j++) {
                    Label fieldNames = new Label(13 + fieldNamecount, 0, list.get(j).getField_name_cn());
                    fieldNamecount++;
                    ws.addCell(fieldNames);
                }
                for (Map<String, Object> stringObjectMap : statisticsList) {
                    if (stringObjectMap.get("ext_json") != null) {
                        //存储 fieldValue
                        JSONArray jsonArray = JSONArray.parseArray(stringObjectMap.get("ext_json").toString());
                        List<String> lists = JSONObject.parseArray(jsonArray.toJSONString(), String.class);
                        List<String> fieldValueList = new ArrayList<>();
                        for (ExtFieldRecord extFieldMap:list) {
                            String fieldName = extFieldMap.getField_name();
                            boolean existFlag = false;
                            for (String extJsonString:lists) {
                                Map<String, Object> mapObj = JSONObject.parseObject(extJsonString, Map.class);
                                String userFieldName = mapObj.get("fieldName") == null ? "" : mapObj.get("fieldName").toString();
                                String userFieldValue = mapObj.get("fieldValue") == null ? "" : mapObj.get("fieldValue").toString();
                                if (fieldName.equals(userFieldName)) {
                                    fieldValueList.add(userFieldValue);
                                    existFlag = true;
                                    break;
                                }
                            }
                            if (!existFlag) {
                                fieldValueList.add("");
                            }
                        }
                        map3.put(stringObjectMap.get("user_uuid").toString(), fieldValueList);
                    }
                }
            }
            // 第二个sheet
            Label questionnaire_name_ws1 = new Label(0, 0, "问卷名称");
            Label user_sex_ws1 = new Label(1, 0, "用户名");
            Label realName_ws1 = new Label(2, 0, "真实姓名");
            Label nick_name_ws1 = new Label(3, 0, "微信昵称");
            Label user_phone_ws1 = new Label(4, 0, "手机号");
            Label whole_name_ws1 = new Label(5, 0, "组织机构");
            Label questionnaire_description_ws1 = new Label(6, 0, "问卷说明");
            ws1.addCell(questionnaire_name_ws1);
            ws1.addCell(user_sex_ws1);
            ws1.addCell(realName_ws1);
            ws1.addCell(nick_name_ws1);
            ws1.addCell(user_phone_ws1);
            ws1.addCell(whole_name_ws1);
            ws1.addCell(questionnaire_description_ws1);
            for (int k = 0; k < statisticsList.size(); k++) {
                // 默认0  1达预警值 2正常
                String waringResults = statisticsList.get(k).get("waring_result").toString();
                if (waringResults.equals("0")) {
                    waringResults = "不预警";
                } else if (waringResults.equals("1")) {
                    waringResults = "达预警值";
                } else if (waringResults.equals("2")) {
                    waringResults = "正常";
                }
                Label name_k_0 = new Label(0, k + 1, waringResults);
                Label name_k_1 = new Label(1, k + 1, statisticsList.get(k).get("questionnaire_name").toString());
                Label name_k_2 = new Label(2, k + 1, statisticsList.get(k).get("user_name") == null ? "" : statisticsList.get(k).get("user_name").toString());
                Label name_k_3 = new Label(3, k + 1, statisticsList.get(k).get("real_name") == null ? "" : statisticsList.get(k).get("real_name").toString());
                Label name_k_4 = new Label(4, k + 1, statisticsList.get(k).get("nick_name") == null ? "" : statisticsList.get(k).get("nick_name").toString());
                Label name_k_5 = new Label(5, k + 1, statisticsList.get(k).get("user_phone") == null ? "" : statisticsList.get(k).get("user_phone").toString());
                Label name_k_6 = new Label(6, k + 1, statisticsList.get(k).get("user_gender").toString().equals("1") ? "男" : "女");
                Label name_k_7 = new Label(7, k + 1, longToSimpleDateFormat(Long.valueOf(String.valueOf(statisticsList.get(k).get("user_birth")))));
                Label name_k_8 = new Label(8, k + 1, statisticsList.get(k).get("whole_name").toString());
                Label name_k_9 = new Label(9, k + 1, statisticsList.get(k).get("submit_date").toString());
                Label name_k_10 = new Label(10, k + 1, map1.get(statisticsList.get(k).get("task_id")));
                Label name_k_11 = new Label(11, k + 1, map2.get(statisticsList.get(k).get("questionnaire_id")));
                TenantQuestionnaireTaskInfo qtask_info_id = tenantQuestionnaireTaskInfoService.selectByPrimaryKey((Long) statisticsList.get(k).get("qtask_info_id"));
                Label name_k_12 = new Label(12, k + 1, qtask_info_id.getAnswer());
                //Label name_k_14 = new Label(12, k + 1, statisticsList.get(k).get("user_phone").toString()== null ? "" : statisticsList.get(k).get("user_phone").toString());
                if (statisticsList.get(k).get("ext_json")!=null) {
                    List user_uuid1 = (List) map3.get(statisticsList.get(k).get("user_uuid").toString());
                    for (int i = 0; i < user_uuid1.size(); i++) {
                            Label name_k_13 = new Label(13 + i, k + 1, user_uuid1.get(i).toString());
                            ws.addCell(name_k_13);
                        }
                }

                //第二个 sheet
                Label name_k_ws0 = new Label(0, k + 1, statisticsList.get(k).get("questionnaire_name").toString());
                Label name_k_ws1 = new Label(1, k + 1, statisticsList.get(k).get("user_name").toString());
                Label name_k_ws2 = new Label(2, k + 1, statisticsList.get(k).get("real_name")== null ? "" : statisticsList.get(k).get("real_name").toString());
                Label nick_name_ws2 = new Label(3, k + 1, statisticsList.get(k).get("nick_name")== null ? "" : statisticsList.get(k).get("nick_name").toString());
                Label user_phone_ws2 = new Label(4, k + 1, statisticsList.get(k).get("user_phone")== null ? "" : statisticsList.get(k).get("user_phone").toString());
                Label name_k_ws3 = new Label(5, k + 1, statisticsList.get(k).get("whole_name").toString());
                Label name_k_ws4 = new Label(6, k + 1, map2.get(statisticsList.get(k).get("questionnaire_id")));

                ResponseData responseData = getTableAllInfos((Long) statisticsList.get(k).get("qtask_info_id"));
                Object mTableAllInfo = responseData.getData().get("mTableAllInfo");
                String mAnswerStr = (String) responseData.getData().get("mAnswerStr");
                List listQuestionTitle = new ArrayList();
                Integer msgcount = k + 1;
                if (mAnswerStr.equals("")) {
                    logger.info("====================第" + msgcount + "条答案为空无法导出！");
                    List questionInfos1 = (List) AssertUtils.getFieldValueByName("questionInfos", mTableAllInfo);
                    for (int s = 0; s < questionInfos1.size(); s++) {
                        QuestionInfos o = (QuestionInfos) questionInfos1.get(s);
                        String questionTitle = (String) AssertUtils.getFieldValueByName("questionTitle", o);
                        System.out.println(questionTitle);
                        listQuestionTitle.add(questionTitle + " (答题详情)");
                    }
                    ws.addCell(name_k_0);
                    ws.addCell(name_k_1);
                    ws.addCell(name_k_2);
                    ws.addCell(name_k_3);
                    ws.addCell(name_k_4);
                    ws.addCell(name_k_5);
                    ws.addCell(name_k_6);
                    ws.addCell(name_k_7);
                    ws.addCell(name_k_8);
                    ws.addCell(name_k_9);
                    ws.addCell(name_k_10);
                    ws.addCell(name_k_11);
                    ws.addCell(name_k_12);
                    ws1.addCell(name_k_ws0);
                    ws1.addCell(name_k_ws1);
                    ws1.addCell(name_k_ws2);
                    ws1.addCell(nick_name_ws2);
                    ws1.addCell(user_phone_ws2);
                    ws1.addCell(name_k_ws3);
                    ws1.addCell(name_k_ws4);
                    Integer rew = 7;
                    for (int t = 0; t < listQuestionTitle.size(); t++) {
                        Label listQuestionTitle1 = new Label(t + rew, 0, listQuestionTitle.get(t).toString());
                        ws1.addCell(listQuestionTitle1);
                        Label name_k_13 = new Label(t + rew, k + 1, "答案信息不存在！");
                        ws1.addCell(name_k_13);
                    }
                    System.out.println("Excel导出成功！");
                    logger.info("========Excel导出成功!");
                    // throw new IllegalArgumentException("====================第" + msgcount + "条答案为空无法导出！");
                } else {
                    String string = answerSubString(mAnswerStr);
                    if (string.contains("没有选项")) {
                        List<String>   answerList = Arrays.stream(string.split("\\|"))
                                .map(s -> String.valueOf(s.trim()))
                                .collect(Collectors.toList());
                        List questionInfos1 = (List) AssertUtils.getFieldValueByName("questionInfos", mTableAllInfo);
                        List listAnswers = new ArrayList();
                        for (int s = 0; s < questionInfos1.size(); s++) {
                            QuestionInfos o = (QuestionInfos) questionInfos1.get(s);
                            String questionTitle = (String) AssertUtils.getFieldValueByName("questionTitle", o);
                            System.out.println(questionTitle);
                            listQuestionTitle.add(questionTitle + " (答题详情)");
                            List answers = (List) AssertUtils.getFieldValueByName("answers", o);
                            String o2 = answerList.get(s);
                            if (o2.equals("没有选项")) {
                                listAnswers.add("没有选项");
                            } else {
                                Object o1 = answers.get(Integer.valueOf(o2) - 1);
                                String answers1 = (String) AssertUtils.getFieldValueByName("answers", o1);
                                System.out.println(answers1);
                                listAnswers.add(answers1);
                            }
                        }
                        ws.addCell(name_k_0);
                        ws.addCell(name_k_1);
                        ws.addCell(name_k_2);
                        ws.addCell(name_k_3);
                        ws.addCell(name_k_4);
                        ws.addCell(name_k_5);
                        ws.addCell(name_k_6);
                        ws.addCell(name_k_7);
                        ws.addCell(name_k_8);
                        ws.addCell(name_k_9);
                        ws.addCell(name_k_10);
                        ws.addCell(name_k_11);
                        ws.addCell(name_k_12);
                        if (statisticsList.get(k).get("ext_json")!=null) {
                            List user_uuid1 = (List) map3.get(statisticsList.get(k).get("user_uuid").toString());
                            for (int i = 0; i < user_uuid1.size(); i++) {
                                Label name_k_13 = new Label(13 + i, k + 1, user_uuid1.get(i).toString());
                                ws.addCell(name_k_13);
                            }
                        }

                        ws1.addCell(name_k_ws0);
                        ws1.addCell(name_k_ws1);
                        ws1.addCell(name_k_ws2);
                        ws1.addCell(nick_name_ws2);
                        ws1.addCell(user_phone_ws2);
                        ws1.addCell(name_k_ws3);
                        ws1.addCell(name_k_ws4);
                        Integer rew = 7;
                        for (int s = 0; s < listQuestionTitle.size(); s++) {
                            Label listQuestionTitle1 = new Label(s + rew, 0, listQuestionTitle.get(s).toString());
                            ws1.addCell(listQuestionTitle1);

                        }
                        for (int s = 0; s < listAnswers.size(); s++) {
                            Label name_k_13 = new Label(s + rew, k + 1, listAnswers.get(s).toString());
                            ws1.addCell(name_k_13);
                        }
                    } else {
//                    if (!mAnswerStr.contains("|")) {
//                        list = new ArrayList<>();
//                        list.add(Integer.valueOf(mAnswerStr));
//                    }else {
                        List<Integer>  answerList = Arrays.stream(mAnswerStr.split("\\|"))
                            .map(s -> Integer.parseInt(s.trim()))
                            .collect(Collectors.toList());
                    //}
                        List questionInfos1 = (List) AssertUtils.getFieldValueByName("questionInfos", mTableAllInfo);
                        logger.info("题目的条数为" + questionInfos1.size());
                        logger.info("答案的条数为" + answerList.size());

                        List listAnswers = new ArrayList();
                        for (int s = 0; s < questionInfos1.size(); s++) {
                            QuestionInfos o = (QuestionInfos) questionInfos1.get(s);
                            String questionTitle = (String) AssertUtils.getFieldValueByName("questionTitle", o);
                            System.out.println(questionTitle);
                            listQuestionTitle.add(questionTitle + " (答题详情)");
                            List answers = (List) AssertUtils.getFieldValueByName("answers", o);
                            Integer o2 = answerList.get(s);
                            Object o1 = answers.get(o2 - 1);
                            String answers1 = (String) AssertUtils.getFieldValueByName("answers", o1);
                            System.out.println(answers1);
                            listAnswers.add(answers1);
                        }
                        ws.addCell(name_k_0);
                        ws.addCell(name_k_1);
                        ws.addCell(name_k_2);
                        ws.addCell(name_k_3);
                        ws.addCell(name_k_4);
                        ws.addCell(name_k_5);
                        ws.addCell(name_k_6);
                        ws.addCell(name_k_7);
                        ws.addCell(name_k_8);
                        ws.addCell(name_k_9);
                        ws.addCell(name_k_10);
                        ws.addCell(name_k_11);
                        ws.addCell(name_k_12);
                        if (statisticsList.get(k).get("ext_json")!=null) {
                            List user_uuid1 = (List) map3.get(statisticsList.get(k).get("user_uuid").toString());
                            for (int i = 0; i < user_uuid1.size(); i++) {
                                Label name_k_13 = new Label(13 + i, k + 1, user_uuid1.get(i).toString());
                                ws.addCell(name_k_13);
                            }
                        }

                        ws1.addCell(name_k_ws0);
                        ws1.addCell(name_k_ws1);
                        ws1.addCell(name_k_ws2);
                        ws1.addCell(nick_name_ws2);
                        ws1.addCell(user_phone_ws2);
                        ws1.addCell(name_k_ws3);
                        ws1.addCell(name_k_ws4);
                        Integer rew = 7;
                        for (int s = 0; s < listQuestionTitle.size(); s++) {
                            Label listQuestionTitle1 = new Label(s + rew, 0, listQuestionTitle.get(s).toString());
                            ws1.addCell(listQuestionTitle1);
                        }
                        for (int s = 0; s < listAnswers.size(); s++) {
                            Label name_k_13 = new Label(s + rew, k + 1, listAnswers.get(s).toString());
                            ws1.addCell(name_k_13);
                        }
                    }
                }
            }
            //写进文档
            wwb.write();
            System.out.println("Excel导出成功！");
            logger.info("========Excel导出成功!");
            // 关闭Excel工作簿对象
            wwb.close();
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (os != null) {
                os.close();
            }
            if(wwb != null){
                os.close();
            }
        }


    }
    public static String longToSimpleDateFormat(Long unixtimestamp) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DateUtil.YYYY_MM_DD);
        String format1 = simpleDateFormat.format(new Date(unixtimestamp * 1000));
        return format1;
    }


    /**
     * 获取问卷列表中的上級問卷和下級问卷
     *
     * @param framework_id
     * @return
     */
    @RequestMapping("/getAllQnListSuperiorsAndsubordinates")    //等于1时获取自己本身还有上下级的问卷    2时获取自己本身和父类的问卷
    @ResponseBody
    public ResponseData getAllQnListSuperiorsAndsubordinates(@RequestParam Long framework_id,String flog,Integer page, Integer pageSize,String name) {
        ResponseData responseData = new ResponseData();
        Map<String, Object> retMap = new HashMap<>();
        List<Map<String, Object>> list = null;
        List<Map<String, Object>> list1 = new ArrayList<>();
        PageInfo pi = new PageInfo();
        if (page != null){
            pi.setCurrentPage(page);}
        if (pageSize != null){
            pi.setPageSize(pageSize);}
        if ("1".equals(flog)) {
            // 获取下级问卷和自己本身
            //获取父级问卷
            TenantFrameworks frameworkById = tenantFrameworksService.getFrameworkById(framework_id);

                Map<String, Object> map = new HashMap<>();
                getframeworkDatas(framework_id, null, map);
                list = tenantQuestionnairesService.getAllQnList(map);
            if (frameworkById.getFather_id() != 0) {
                String treePath = frameworkById.getTree_path();
                List<Long> listTreePath = Arrays.stream(treePath.substring(1).split("/"))
                        .map(s -> Long.parseLong(s.trim()))
                        .collect(Collectors.toList());
                listTreePath.remove(listTreePath.size() - 1);
                for (Long aLong : listTreePath) {
                    Map<String, Object> frameworkIdMap = new HashMap();
                    frameworkIdMap.put("frameworkId", aLong);
                    List<Map<String, Object>> maps = tenantQuestionnairesService.listAllTenantQuestionnaires(null,frameworkIdMap,null);
                    for (Map<String, Object> stringObjectMap : maps) {
                        list.add(stringObjectMap);
                    }
                }
            }
            retMap.put("list", list);
        } else {
            //获取父级问卷和本身问卷
            TenantFrameworks frameworkById = tenantFrameworksService.getFrameworkById(framework_id);
            String treePath = frameworkById.getTree_path();
            if (frameworkById.getFather_id() == 0) {
                String Father_id = treePath.replace("/", "");
                Map<String, Object> frameworkIdMap = new HashMap();
                frameworkIdMap.put("frameworkId", Father_id);
                List<Map<String, Object>> maps = tenantQuestionnairesService.listAllTenantQuestionnaires(pi,frameworkIdMap,name);
                for (Map<String, Object> stringObjectMap : maps) {
                    list1.add(stringObjectMap);

                }
            }else {
                List<Long> listTreePath = Arrays.stream(treePath.substring(1).split("/"))
                        .map(s -> Long.parseLong(s.trim()))
                        .collect(Collectors.toList());
                for (Long aLong : listTreePath) {
                    Map<String, Object> frameworkIdMap = new HashMap();
                    frameworkIdMap.put("frameworkId", aLong);
                    List<Map<String, Object>> maps = tenantQuestionnairesService.listAllTenantQuestionnaires(pi,frameworkIdMap,name);
                    for (Map<String, Object> stringObjectMap : maps) {
                        list1.add(stringObjectMap);
                    }
                }

            }
            retMap.put("list", list1);
            retMap.put("count",list1.size());
        }

        responseData.setData(retMap);
        return responseData;
    }
    public static String answerSubString(String answerString) {
        String s=answerString;
        //截取字符串的第一个字符
        String startString = s.substring(0,1);
        //截取字符串的最后一个字符
        String endString = s.substring(s.length() - 1);
        //第一个字符如果是“|”，则用“没有选项”代替
        if(startString.equals("|")){
            s="没有选项"+s;
        }
        //最后一个字符如果是“|”，则用“没有选项”代替
        if(endString.equals("|")){
            s+="没有选项";
        }
        //实例此时内容为“没有选项|1|1|1|没有选项”，然后分割，对中间没有选择的进行处理
        String[] strings = s.split("\\|");
        for (int i = 0; i < strings.length; i++) {
            //假设只有1，2两个选项，如果不是1且不是2，则填充“没有选项”
            if((strings[i].equals(""))){
                strings[i]="没有选项";
            }
        }

        String result="";
        //遍历字符串数组，拼凑结果集
        for (int i = 0; i <strings.length ; i++) {
            result=result+strings[i]+"|";
        }
        //拼凑后，最后会多一个“|”
        // System.out.println(result);
        //去除最后的“|”的最终结果
        System.out.println(result.substring(0,result.length()-1));
        return result.substring(0,result.length()-1);
    }






}